Ruby-on-Rails:多个has_many:通过可能吗?

64

在Rails中,是否可能拥有多个互相通过has_many:through关系的联系?我收到了这个建议作为我发表的另一个问题的解决方案,但一直无法使其正常工作。

朋友是通过一个连接表进行循环关联。目标是创建一个has_many:through关于friends_comments,这样我就可以通过单个查询获得某个User的所有朋友的评论,比如使用user.friends_comments

class User
  has_many :friendships
  has_many :friends, 
           :through => :friendships,
           :conditions => "status = #{Friendship::FULL}"
  has_many :comments
  has_many :friends_comments, :through => :friends, :source => :comments
end

class Friendship < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, :class_name => "User", :foreign_key => "friend_id"
end

我觉得这个方案很棒,也很有道理,但是对我来说还不起作用。当我尝试访问用户的好友评论时,我得到了以下相关部分的错误信息:
ERROR: column users.user_id does not exist
: SELECT "comments".* FROM "comments" INNER JOIN "users" ON "comments".user_id = "users".id WHERE (("users".user_id = 1) AND ((status = 2)))

当我只输入user.friends时,它可以工作,它执行的查询如下:
: SELECT "users".* FROM "users" INNER JOIN "friendships" ON "users".id = "friendships".friend_id WHERE (("friendships".user_id = 1) AND ((status = 2)))

因此,它似乎完全忘记了原始的has_many的友谊关系,然后不适当地尝试使用User类作为联接表。

我是否做错了什么,或者这根本不可能?

4个回答

81

编辑:

Rails 3.1支持嵌套关联。例如:

has_many :tasks
has_many :assigments, :through => :tasks
has_many :users, :through => :assignments

以下的解决方案是不必要的。请参考这个视频教程获取更多详情。

原回答

你正在将一个has_many :through关联作为另一个has_many :through关联的源进行传递。我认为它不会起作用。

  has_many :friends, 
           :through => :friendships,
           :conditions => "status = #{Friendship::FULL}"
  has_many :friends_comments, :through => :friends, :source => :comments
你有三种方法来解决这个问题。
1) 编写关联扩展。
 has_many  :friends, 
           :through => :friendships,
           :conditions => "status = #{Friendship::FULL}" do
     def comments(reload=false)
       @comments = nil if reload 
       @comments ||=Comment.find_all_by_user_id(map(&:id))
     end
 end

现在您可以按照以下方式获取朋友的评论:

user.friends.comments

2) 给 User 类添加一个方法。

  def friends_comments(reload=false)
    @friends_comments = nil if reload 
    @friends_comments ||=Comment.find_all_by_user_id(self.friend_ids)
  end

现在,您可以按照以下方式获取好友的评论:

user.friends_comments

3) 如果您希望这个过程更加高效,则:

  def friends_comments(reload=false)
    @friends_comments = nil if reload 
    @friends_comments ||=Comment.all( 
             :joins => "JOIN (SELECT friend_id AS user_id 
                              FROM   friendships 
                              WHERE  user_id = #{self.id}
                        ) AS friends ON comments.user_id = friends.user_id")
  end

现在可以按照以下方法获取朋友的评论:

user.friends_comments

所有方法都会缓存结果。如果您希望重新加载结果,请执行以下操作:

user.friends_comments(true)
user.friends.comments(true)

或者更好的做法:

user.friends_comments(:reload)
user.friends.comments(:reload)

1
不幸的是,这种方法背后的原始目的是为了让我能够在一个查询中获取SQL中所有朋友的评论。请参见此处: http://stackoverflow.com/questions/2382642/ruby-on-rails-how-to-pull-out-most-recent-entries-from-a-limited-subset-of-a-dat如果我编写一个函数,那将导致N+1个查询。 - William Jones
1
不,它不会。这将是两个查询。第一个查询是获取朋友,第二个查询是获取所有朋友的评论。如果您已经将好友加载到用户模型中,则不会产生任何费用。我已经使用了另外两种方法更新了解决方案。看一下。 - Harish Shetty
@williamjones 在这三种方法中,你不会遇到N+1问题。你可以检查日志文件以确保这一点。个人而言,我喜欢第一种方法,因为它非常优雅,即user.friends.commentsuser.friends_comments更好。 - Harish Shetty
请问您能解释一下第一个解决方案中 find_all_by_users_id 的参数吗?我会非常感激。 - James
@James:Rails 提供了两种类型的动态查找器:单行(find_by)和多行(find_all_by)。find_all_by_user_id 是一种多行动态查找器。请阅读 Rails 文档以获取更多详细信息:http://guides.rubyonrails.org/active_record_querying.html#dynamic-finders - Harish Shetty

8

有一个插件可以解决你的问题,可以看看这篇博客

你可以使用以下命令安装插件:

script/plugin install git://github.com/ianwhite/nested_has_many_through.git

5

虽然过去这种方式不能正常工作,但在Rails 3.1中已经可以很好地运行。


3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接