Forum: Ruby on Rails join table attributes piggy backed with has_many through

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.
Eric G. (Guest)
on 2007-05-20 10:06
Is there anyway to get the join table attributes to show up as
attributes on the has_many association when the has_many is eager
loaded. I think the eager loaded part is the gotcha to all this.

For example, if I have book.contributors, and the join table
"contributions" had a contribution_date on it. How can I get the date
onto the contributors' objects.

That way I can do book.contributors[0].contribution_date. Is it not
possible to do when its included?
Mark Reginald J. (Guest)
on 2007-05-20 15:20
(Received via mailing list)
Aryk G. wrote:
> Is there anyway to get the join table attributes to show up as
> attributes on the has_many association when the has_many is eager
> loaded. I think the eager loaded part is the gotcha to all this.
>
> For example, if I have book.contributors, and the join table
> "contributions" had a contribution_date on it. How can I get the date
> onto the contributors' objects.
>
> That way I can do book.contributors[0].contribution_date. Is it not
> possible to do when its included?

The attributes should be there if you're using has_and_belongs_to_many.

But if you're using has_many_through, eager load like this

  book = Book.find(..., :include => {:contributions => :contributor})

Then access like this:

  book.contributions[0].contribution_date
  book.contributions[0].contributor.name

--
We develop, watch us RoR, in numbers too big to ignore.
This topic is locked and can not be replied to.