gpt4 book ai didi

ruby-on-rails - ruby rails : Retrieving a friendship given two users

转载 作者:数据小太阳 更新时间:2023-10-29 08:13:40 28 4
gpt4 key购买 nike

我在这里看过关于 self 参照关系的 railscast:http://railscasts.com/episodes/163-self-referential-association

我在此基础上添加了一个关于友谊的“状态”字段,以便必须请求和接受友谊。 'status' 是一个 bool 值——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

这是我的代码:用户.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"

当我这样做时——为了显示用户的 friend ,我必须同时显示“current_user.friends”“current_user.inverse_friends”——有没有有什么方法可以调用 "current_user.friends" 并将其加入两者?

最佳答案

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

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)

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

关于ruby-on-rails - ruby rails : Retrieving a friendship given two users,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6735920/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com