Forum: Ruby on Rails Rails, associations, eager-loading

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
E51c6ae07e72cf04ef869868cb8eca6e?d=identicon&s=25 Jake Janovetz (Guest)
on 2005-11-14 17:03

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

class Committee < ActiveRecord::Base
  has_and_belongs_to_many :persons

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|              # Retrieve committee member name
    if not c.alternate.nil?    # Retrieve alternate name

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

This topic is locked and can not be replied to.