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

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