It is often the case when I iterate over an array of objects in a
has_many_through association that I want access to both the :has_many
objects and the :through objects. There is generally something in
that join object that is useful to get at, but enumerating with the
each method, I don't have easy access to that join object.
Example:
class User < ActiveRecord::Base
has_many :memberships
has_many :groups, :through => :memberships
end
# ugly way
user.groups.each do |group|
membership = user.memberships.detect { |memberships|
memberships.group_id == group.id}
# or
membership = user.memberships.find(:first, :conditions =>
["memberships.group_id = ?", group.id]}
puts "#{group.name}, #{membership.status}"
end
# a better way
user.groups.each_with_join do |group, membership|
puts "#{group.name}, #{membership.status}"
end
I created a ticket with a patch (tested) in lighthouse:
http://rails.lighthouseapp.com/projects/8994/tickets/82-iterate-over-has_many-array-with-the-join-through-model
Let me know what you think!
Daniel
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Core" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/rubyonrails-core?hl=en
-~----------~----~----~----~------~----~------~--~---