我在这里看到了关于自我参照关系的 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”并让它成为两者的结合?