Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I access a has_many :through association object's relevant join model without additional queries?
    primarykey
    data
    text
    <p>This is something I've come across a number of times now and I'd love to either figure out how to do what I'm wanting or build and submit a patch to Rails that does it. Many times in my apps I'll have some models that look something like this:</p> <pre><code>class User &lt; 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 </code></pre> <p>What I want to be able to do is access the relevant membership from a call to the association without doing additional queries. For instance, I <strong>want</strong> to do something like this:</p> <pre><code>@group = Group.first @group.users.each do |user| membership = user.membership # this would be the membership for user in @group end </code></pre> <p>Is there anything in Rails that allows this? Because the only methods I know to achieve the result I'm talking about are terribly ugly and inefficient, something like this:</p> <pre><code>@group.users.each do |user| membership = Membership.where(group_id: @group.id, user_id:user.id).first end </code></pre> <p>Does ActiveRecord have some arcane in-built facility to achieve this? It seems like it wouldn't be too hard, it's already having to fetch the join model in order to properly retrieve the association anyway so if this functionality doesn't exist it seems to me it should. I've run into this a number of times and am ready to roll up my sleeves and solve it for good. What can I do?</p> <p><strong>Update:</strong> The other pattern for this that I could use that basically gets what I want is something like this:</p> <pre><code>@group.memberships.includes(:user).each do |membership| user = membership.user end </code></pre> <p>But aesthetically I don't like this solution because I'm not actually interested in the memberships so much as I am the users and it feels wrong to be iterating over the join model instead of the association target. But this is better than the other way I pointed out above (thanks to Ian Yang of Intridea for reminding me of this one).</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload