问题描述
试图找出相互关系,在一个朋友的关系,已经有朋友和inverse_friends。但如何将它们结合起来,以获得共同的朋友吗的似乎无法弄清楚我试了几个选项和搜索长时间上网,只是看不到它的
的has_many:友谊
的has_many:朋友:通过=> :友谊
的has_many:inverse_friendships,:将class_name => 友谊,:foreign_key => friend_id
的has_many:inverse_friends,:通过=> :inverse_friendships,:源=> :用户
如何获得
的has_many:mutual_friends?
我不认为你可以定义一个共同的朋友关系。那么,让我们来看看一个共同的朋友类的方法和范围。
我认为我们希望所有的朋友,对他们来说,我们是他们的朋友。
类用户
的has_many:友谊
的has_many:朋友:通过=> :友谊
的has_many:inverse_friendships,:将class_name => 友谊,:foreign_key => friend_id
的has_many:inverse_friends,:通过=> :inverse_friendships,:源=> :用户
高清mutual_friends
inverse_friends.joins(:友谊)。凡(friendships.user_id = users.id和friendships.friend_id =:self_id:self_id => ID)。所有
结束
结束
要做到这一点作为一个协会,这将是你正在尝试做的:
的has_many:mutual_friends,
:通过=> :inverse_friendships,
:源=> :用户,
:条件=> [friendships.user_id = users.id和friendships.friend_id =:self_id:self_id => ID]
现在的问题是与ID的方法调用中的has_many:mutual_friends关联定义
Trying to find the mutual relation, In a friends relations, Already have friends and inverse_friends. But how to combine them to get the mutual friends? Cannot seem to figure it out I tried several options and searched long time online, just don't see it
has_many :friendships
has_many :friends, :through => :friendships
has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id"
has_many :inverse_friends, :through => :inverse_friendships, :source => :user
how to get a
has_many :mutual_friends ?
I don't think you can define a mutual friends association. So, let's look at a mutual friends class method or scope.
I assume that we want all our friends, for whom we are their friend.
class User
has_many :friendships
has_many :friends, :through => :friendships
has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id"
has_many :inverse_friends, :through => :inverse_friendships, :source => :user
def mutual_friends
inverse_friends.joins(:friendships).where("friendships.user_id = users.id and friendships.friend_id = :self_id", :self_id => id).all
end
end
To do it as an association, this would be what you are trying to do:
has_many :mutual_friends,
:through => :inverse_friendships,
:source => :user,
:conditions => ["friendships.user_id = users.id and friendships.friend_id = :self_id", :self_id => id]
The problem is with the id method call in the has_many :mutual_friends association definition.
这篇关于导轨的ActiveRecord,朋友关系+ inverse_friend关系如何得到的相互关系?包括code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!