This is what I met several times now, and I would like to either figure out how to do what I want, or create and send a Rails patch that does this. Many times in my applications I will have some models that look something like this:
class User < ActiveRecord::Base has_many :memberships has_many :groups, through: :memberships end class Membership belongs_to :user belongs_to :group def foo # something that I want to know end end class Group has_many :memberships has_many :users, through: :memberships end
What I want to do is access the appropriate membership from the call to the association without additional requests. For example, I want to do something like this:
@group = Group.first @group.users.each do |user| membership = user.membership
Is there anything in Rails that allows this? Since the only methods that I know to achieve the result I'm talking about are terribly ugly and ineffective, something like this:
@group.users.each do |user| membership = Membership.where(group_id: @group.id, user_id:user.id).first end
Does ActiveRecord have several built-in tools to create this goal? It seems that this would not be too complicated, he already had to take the connection model in order to get the association in any case, so if this function does not exist, it seems to me that it should. I have come across this several times and am ready to roll up my sleeves and solve it forever. What can I do?
Update: Another template for this, which I could use, basically gets what I want, looks something like this:
@group.memberships.includes(:user).each do |membership| user = membership.user end
But aesthetically, I donβt like this solution, because Iβm actually not interested in membership, since I am a user, and it seems to me wrong to sort through the connection model, and not the purpose of the association. But this is better than I indicated above (thanks to Jan Jan from Intridea to remind me of this).