我有一个用户模型。
我有一个朋友模型,其中包含invitee_id和Inviter_id列以及状态。状态用作标记是否已接受好友请求。 Inviter_id是发送好友请求的用户的id,invitee_id是接收好友请求的用户。请检查内联评论。
class User < ActiveRecord::Base
has_many :friends // now i want to search all the friends with accepted friend request. (sent or received both.)
has_many :pending_friend_requests,:class_name => "Friend", :foreign_key=>"invitee_id", :conditions => {:status => 0}
end
class Friend < ActiveRecord::Base
end
问题是如何用已接受的朋友请求获取所有朋友..发送或接收因为有两个外来列。 invitee_id或Inviter_id
答案 0 :(得分:0)
如果我的问题是对的,那么screencast就是您所需要的。
更新
你认为你不这样做,我想,你确实需要一种自我引用的多对多关系。
您可以创建命名范围,而不是为待处理请求建立关联。之后,您可以通过User.find(params[:id]).friends.accepted
收到您邀请的所有朋友。
我无法理解的是,您是否希望user.friends检索邀请我的人以及我邀请的人或其中一人。
由于你的名字(邀请者和被邀请者),我认为这是第二种情况。它在屏幕录像中被覆盖。这是通过创建额外的倒置关联来完成的(Ryan最后谈到了这一点)。
但如果它是第一个,最简单的解决方案是为每个inviter-invitee对创建两行。您可以使用此gem来简化操作,但它的行为与我说的相同。
如果没有帮助,请尝试指定您的问题。
答案 1 :(得分:0)
has_many
设置关系。使用scope
作为条件。
class User < ActiveRecord::Base
has_many :invitees, :through => :friends
has_many :friends, :foreign_key=>"inviter_id"
def accepted_invitees
invitees.where(:friends => {:accepted => true })
end
end
class Friend < ActiveRecord::Base
belongs_to :invitee, :class_name => "User"
belongs_to :inviter, :class_name => "User"
# needs accepted column
end
然而,由于模型和列的设置方式,这是令人困惑的方法。如果我这样做,我会做类似的事情:
class User < ActiveRecord::Base
has_many :friends, :through => :friendships
has_many :friendships
def accepted_friends
friends.where(:friendships => {:accepted => true })
end
end
class Friendships < ActiveRecord::Base
belongs_to :user # change inviter_id to user_id
belongs_to :friend, :class_name => "User" # change invitee_id to friend_id
# needs accepted column
end