Skip to content

Instantly share code, notes, and snippets.

@JonahMoses
Created August 5, 2015 18:40
Show Gist options
  • Save JonahMoses/01a9cbbc2874fa0e937c to your computer and use it in GitHub Desktop.
Save JonahMoses/01a9cbbc2874fa0e937c to your computer and use it in GitHub Desktop.
class Employee < ActiveRecord::Base
end
class Manager < Employee
self.table_name = 'employees'
has_many :engineers
def nearest_manager
self
end
end
class Engineer < Employee
self.table_name = 'employees'
belongs_to :nearest_manager, class_name: 'Manager'
end
# want to be able to say:
Employee.all.includes(:nearest_manager)
# ... and get back a collection of mixed Manager and Employee instances, where
# the nearest_manager method on Managers just returns self, and the
# nearest_manager association on Engineers is preloaded using a single batch SQL
# query
@srt32
Copy link

srt32 commented Aug 5, 2015

Do you not need some kind of role column to denote which kind of employee should be? Unless you're using a type column?

Similar to the below I think:

# app/models/tribe.rb
class Tribe < ActiveRecord::Base 
    has_many :animals 
end

# app/models/animal.rb
class Animal < ActiveRecord::Base 
    belongs_to :tribe 
    self.inheritance_column = :race 

    # We will need a way to know which animals
    # will subclass the Animal model
    def self.races
      %w(Lion WildBoar Meerkat)
    end

end

class Lion < Animal; end 
class Meerkat < Animal; end 
class WildBoar < Animal; end

@srt32
Copy link

srt32 commented Aug 5, 2015

Is there a nearest_manager_id column? If so, could you not do

class Manager < Employee
  self.table_name = 'employees'
  has_many :engineers

  belongs_to :nearest_manager, class_name: 'Manager'
  # I think this will work if you set this manager's nearest_manager_id to its own id.
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment