Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Active Record to Find a Join Table

I have several models associated with a :has_many => :through relationship:

class User < ActiveRecord::Base
  has_many :group_members
  has_many :groups, :through => :group_members
end

class Group < ActiveRecord::Base
  has_many :group_members
  has_many :users, :through => :group_members
end

class GroupMembers < ActiveRecord::Base
  belongs_to :group
  belongs_to :user
end

It's easy to find the relationships between groups and users with ActiveRecord:

groups = @user.groups
users = @group.users

But what if I wanted to find the join table that a group and a user share? Right now the best solution I can come up with is to use a class method. For instance, in the User model I have:

def group_member_for(group)
    self.group_members.where(:group_id => group.id).first
end

This works fine, but I suspect there's a cleaner approach. Perhaps even an approach that directly uses ActiveRecord associations. Something like:

group_member = @user.groups.group_member
like image 454
nullnullnull Avatar asked Jan 17 '13 17:01

nullnullnull


1 Answers

You can simply do the following:

user.group_members
# and
group.group_members
# or
GroupMember.where(user_id: user.id, group_id: group.id)
like image 130
MrYoshiji Avatar answered Sep 18 '22 03:09

MrYoshiji