Rails, associations, eager-loading


#1

Hello-

I have a join table setup to associate ‘committee’ with ‘person’, but
also want to have an ‘alternate’ in there. For me, it makes more sense
to have the ‘alternate’ tied to the ‘person’ rather than a more
complicated other association or something. However, the ‘alternate’
could be 0 (i.e. no alternate assigned)

Tables are:

  • persons
  • committees
  • committees_persons

I think the Ruby should look like:

class Person < ActiveRecord::Base
has_and_belongs_to_many :committees
end

class Committee < ActiveRecord::Base
has_and_belongs_to_many :persons
end

This part works fine, but I’d also like to add support for the
‘alternate’ and I’m wondering how best to do it. I’d like it to be
eager-loaded just like ‘person’ is, so I can do things like:

@committee.persons.each do |c|
c.name # Retrieve committee member name
if not c.alternate.nil?
c.alternate.name # Retrieve alternate name
end
end

Is this possible? If so, how? Can I do eager-loading if ‘alternate’
may be 0?

Thanks,
Jake