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
You can simply do the following:
user.group_members
# and
group.group_members
# or
GroupMember.where(user_id: user.id, group_id: group.id)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With