活动记录,其中外键可以是两列中的任何一个

| 我有一个用户模型。 我有一个Friend模型,其中包含columne_id和Inviter_id和状态列。无论是否接受好友请求,状态均用作标记。 Inviter_id是发送朋友请求的用户的ID,inviter_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
问题是如何获取所有已接受好友请求的好友..因为有两个外部列,所以已发送或接收。邀请对象编号或邀请对象编号     
已邀请:
        如果我的问题正确无误,那么此截屏视频就是您所需要的。 更新 我认为,尽管您说您不需要,但您确实需要自指的多对多关系。 可以为命名的作用域建立关联,而不是为未决的请求建立关联。之后,您将得到
User.find(params[:id]).friends.accepted
邀请的所有朋友。 我不明白的是,您是否要让user.friends检索邀请我的人和我邀请的人,或者只检索其中之一。 由于您的名字(邀请者和被邀请者),我想这是第二种情况。它已在截屏中涵盖。这是通过创建其他反向关联来完成的(Ryan最后谈到了该关联)。 但是,如果这是第一个,最简单的解决方案是为每个邀请者-被邀请者对创建两行。您可以使用此gem简化事情,但其行为与我告诉的相同。 如果没有帮助,请尝试指定您的问题。     
        
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
    

要回复问题请先登录注册