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

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
E51c6ae07e72cf04ef869868cb8eca6e?d=identicon&s=25 Jake Janovetz (Guest)
on 2005-11-14 17:03
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
This topic is locked and can not be replied to.