Using an active record to look up a join table

I have several models related to the relation :has_many => :through :

 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 

Easily find relationships between groups and users with ActiveRecord:

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

But what if I wanted to find a connection table shared by a group and a user? Currently, the best solution I can come up with is to use a class method. For example, in the User model, I:

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

This works great, but I suspect there is a cleaner approach. Perhaps even an approach that directly uses ActiveRecord associations. Sort of:

 group_member = @user.groups.group_member 
+4
source share
1 answer

You can simply do the following:

 user.group_members # and group.group_members # or GroupMember.where(user_id: user.id, group_id: group.id) 
+6
source

All Articles