I’ve been stuck on this all day. I have a setup like the one below. I’m trying to define friends using the group_memberships association.
class User < ActiveRecord::Base has_many :group_memberships has_many :groups, :through => :group_memberships has_many :friends # what goes here? << end class GroupMembership < ActiveRecord::Base belongs_to :user belongs_to :role belongs_to :group end class Role < ActiveRecord::Base has_many :group_memberships end class Group < ActiveRecord::Base has_many :group_memberships has_many :users, :through > :group_memberships end
I’d like to do this without creating a join table for friends, unless it’s completely crazy to do it without.
The group_membership table contains user_id and group_id linking one user to one group.
I’d trying to get
@user.friends
to return users with common group_memberships using the group_id.
has_many :friends, :through => :group_memberships, :source => :group
Nothing I’ve tried works, but I’ll chalk that up to my complete misunderstanding of the above code.
Unfortunately Rails doesn’t let you nest has_many’s more than 2 deep.. Forgetting about naming it
friendsfor a moment (let’s call itusersinstead), this would theoretically be what you’d want:Except that this doesn’t work. If you try it you’ll see this not-so-helpful error message which comes from this bit of code, specifically
source_reflection.options[:through].nil?. That is, thethroughisn’t allowed to have athroughitself.Instead, you may want to do something like this:
Solution 1
Solution 2
Use the
nested_has_many_throughplugin that Radar mentioned. It looks like at least one fork of it on github has been updated to work on the latest Rails.Solution 3 (just for kicks)
or, just for kicks, you could do it with one big SQL query: