【问题标题】:rails activerecord, friend relation + inverse_friend relation how to get the mutual relation? code includedrails activerecord,朋友关系+ inverse_friend关系如何获得相互关系?包含代码
【发布时间】:2012-09-17 22:44:15
【问题描述】:

试图找到相互关系,在朋友关系中,已经有朋友和inverse_friends。但是如何将它们结合起来得到共同的朋友呢? 似乎无法弄清楚我尝试了几个选项并在网上搜索了很长时间,只是没有看到它

  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

如何获得

has_many :mutual_friends ?

【问题讨论】:

  • 如果您发布了表定义,解决您的问题会更容易,这样我们就不必猜测您的架构。

标签: ruby-on-rails activerecord mutual-friendship


【解决方案1】:

你需要两个模特来找到共同的朋友吗?

你就不能这样做

@mutualfriends = @user1.friends & @user2.friends

【讨论】:

  • mutual_friends,我认为他的意思是互惠的友谊。即友谊表中有一个 user1.id|user2.id 条目和一个 user2.id|user1.id 条目。
  • 这是一个优雅的解决方案。但有一个小缺点:它返回Array,因此您可能无法发送要发送给ActiveRecord 对象的方法。 (即分页、装饰等)
【解决方案2】:

我不认为你可以定义一个共同的朋友协会。那么,让我们看一下共同朋友类的方法或作用域。

我假设我们想要我们所有的朋友,我们是他们的朋友。

class User
  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

  def mutual_friends
    inverse_friends.joins(:friendships).where("friendships.user_id = users.id and friendships.friend_id = :self_id", :self_id => id).all
  end
end

要作为一个关联来做,这就是你想要做的:

has_many :mutual_friends,
         :through => :inverse_friendships,
         :source => :user,
         :conditions => ["friendships.user_id = users.id and friendships.friend_id = :self_id", :self_id => id]

问题在于 has_many :mutual_friends 关联定义中的 id 方法调用。

【讨论】:

  • 我有一个粗略的想法,这可以使用 def 方法解决,但是当我尝试使用“for user in”访问视图中的数据时,尝试您的解决方案会引发未定义的局部变量或方法“inverse_friends” User.mutual_friends 将@user.username 放在末尾​​span>
  • 如果你想要一个额外的 .where 语句,如何处理? .where('game_id = 1)。没有工作。谢谢
  • 它应该与另一个地方,之前或之后。但是,由于所有的连接和连接到同一个表,您可能需要使用表名“friendships.game_id”来限定 game_id,并且您可能需要查看日志中的 SQL 以了解 ActiveRecord 是如何命名的连接到同一个表的表。 (查看 SQL,您可能会解决关联问题。我在帮助下编辑了答案,也许是使用关联的提示。)
  • 在主键下查看guides.rubyonrails.org/…
【解决方案3】:

在这里尝试两个查询的交集是一个关于那个的线程

Intersection of two relations

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多