Ruby on Rails:为两个用户检索友谊

时间:2011-07-18 16:12:53

标签: ruby-on-rails ruby relationship self-reference

我在这里看到了关于自我引用关系的railscast:http://railscasts.com/episodes/163-self-referential-association

我已经建立在这个基础之上,因为我在友谊中包含了一个“状态”字段,因此必须要求和接受友谊。 'status'是一个布尔值 - false表示尚未响应,true表示接受。

我的问题是在给出current_user(我正在使用Devise)和另一个用户的情况下找到一个查找友谊对象的方法。

以下是我可以使用的内容:

current_user.friends              # lists people you have friended
current_user.inverse_friends      # lists people who have friended you
current_user.friendships          # lists friendships you've created
current_user.inverse_friendships  # lists friendships someone else has created with you
friendship.friend                 # returns friend in a friendship

我希望获得类似以下的方法,以便我可以轻松查看友情状态:

current_user.friendships.with(user2).status

这是我的代码: user.rb

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

friendship.rb

belongs_to :user
belongs_to :friend, :class_name => "User"

在我看到它时 - 要显示用户的朋友,我必须同时显示“current_user.friends”“current_user.inverse_friends” - 是否存在任何方式只能调用“current_user.friends”并让它成为两者的连接?

1 个答案:

答案 0 :(得分:0)

您可以将条件传递给给定的关联:

has_many :friends, :class_name => 'User', :conditions => 'accepted IS TRUE AND (user = #{self.send(:id)} || friend = #{self.send(:id)})"'

注意:我们使用send,因此在尝试获取属性之前,它不会评估属性。

如果你真的想要“.with(user2)”语法,那么你可以通过named_scope来做到这一点,例如

Class Friendship
  named_scope :with, lambda { |user_id|
      { :conditions => { :accepted => true, :friend_id => user_id } }
    }
end

应该允许:

user1.friendships.with(user2.id)

注意:代码未经过测试 - 您可能需要修复错误...