This code is taken from a previous question, but my question directly relates to it, so I've copied it here:
class User < ActiveRecord::Base
has_many :group_memberships
has_many :groups, :through => :group_memberships
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
New Question Below
How you take the above code one step further and add and work with friends?
class User < ActiveRecord::Base
has_many :group_memberships
has_many :groups, :through => :group_memberships
has_many :friends # what comes here?
has_many :actions
end
In the code above I also added actions. Let's say that the system kept track of each user's actions on the site. How would you code this so that each action was unique and sorted with the most recent at the top for all the user's friends?
<% for action in @user.friends.actions %>
<%= action.whatever %>
<% end %>
The code above may not be valid, you could do something like what I have below, but then the actions wouldn't be sorted.
<% for friend in @user.friends %>
<% for action in friend.actions %>
<%= action.whatever %>
<% end %>
<% end %>
UPDATE
I guess the real issue here is how to define friends? Do I create a new model or join table that links users to other users? Ideally, I'd like to define friends through the common group memberships of other users, but I'm not sure how to go about defining that.
has_many :friends, :through => :group_memberships, :source => :user
But that doesn't work. Any ideas or best practice suggestions?