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
source share