0

我有一个用户模型。活动记录外键可以是任意两列

我有一个朋友模型列Invited_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

那么是什么问题? – bor1s 2011-06-11 15:40:41

+0

@ bor1s的问题是如何获取接受朋友请求的所有朋友..发送或接收 – 2011-06-11 15:44:11

+0

因此,我看到你的Frien模型中没有user_id,所以你可以在你的关系中使用类似这样的东西:has_many:friends,: foreign_key =>“invitee_id”,然后只是user.friends。我认为应该让所有的朋友都不要问他们有什么状态 – bor1s 2011-06-11 15:54:30

回答

0

如果我的问题是正确的,那么这个screencast就是你需要的。

更新

Altough你说你不这样做,我想,你需要一个自我指涉的许多一对多的关系。 而不是为待处理的请求建立关联,您可以创建一个命名作用域。之后,您可以通过User.find(params[:id]).friends.accepted获得您邀请的所有朋友。

我无法理解的是,你是否希望user.friends检索邀请我和那些邀请我的人或者只有其中的一个。

因为你的名字(邀请人和被邀请人),我想这是第二种情况。它在屏幕录像中被覆盖。这是通过创建额外的倒转协会来完成的(Ryan在最后谈到了这一点)。

但是,如果它是第一个,最简单的解决方案就是为每个邀请者 - 被邀请者配对两行。你可以用这个gem来简化一些事情,但它的行为和我说的一样。

如果没有帮助,请尝试指定您的问题。

+0

我不寻找自我指涉关系.. – 2011-06-11 16:37:13

+0

我有两列。即invitee_id和inviter_id,如果我向您发送好友请求,则我的user_id将保存在inviter_id中,并且您的user_id将保存在Invitee_id中。所以,如果我做了这些事情告诉我你,那么在那个事业中,我将得到我向朋友请求的所有朋友。 – 2011-06-11 16:38:03

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 
+0

yaa似乎我做错了..让我检查一下,我会肯定回来。 – 2011-06-12 18:34:50