3

我在这里看到了关于自我参照关系的 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

友谊.rb

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

当我这样做时——要显示用户的朋友,我必须同时显示“current_user.friends”“current_user.inverse_friends” ——有什么方法可以调用“current_user.friends”并让它成为两者的结合?

4

1 回答 1

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)

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

于 2011-07-18T17:47:35.473 回答