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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2383479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:21:29  来源:igfitidea点击:

Ruby-on-Rails: Multiple has_many :through possible?

ruby-on-railsassociationshas-many-through

提问by William Jones

Is it possible to have multiple has_many :throughrelationships that pass through each other in Rails? I received the suggestion to do so as a solution for another question I posted, but have been unable to get it to work.

has_many :through在 Rails 中是否可以有多个相互传递的关系?我收到了这样做的建议,作为我发布的另一个问题的解决方案,但一直无法让它发挥作用。

Friends are a cyclic associationthrough a join table. The goal is to create a has_many :throughfor friends_comments, so I can take a Userand do something like user.friends_commentsto get all comments made by his friends in a single query.

朋友是通过连接表的循环关联。目标是创建一个has_many :throughfor friends_comments,因此我可以使用 aUser并做一些事情,例如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

This looks great, and makes sense, but isn't working for me. This is the error I'm getting in relevant part when I try to access a user's friends_comments:
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)))

这看起来很棒,也很有道理,但对我不起作用。这是我在尝试访问用户的朋友评论时在相关部分遇到的错误:
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)))

When I just enter user.friends, which works, this is the query it executes:
: SELECT "users".* FROM "users" INNER JOIN "friendships" ON "users".id = "friendships".friend_id WHERE (("friendships".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)))

So it seems like it's entirely forgetting about the original has_manythrough friendship relationship, and then is inappropriately trying to use the User class as a join table.

所以它似乎完全忘记了原来的has_many通过友谊关系,然后不恰当地尝试使用 User 类作为连接表。

Am I doing something wrong, or is this simply not possible?

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

回答by Harish Shetty

Edit:

编辑:

Rails 3.1 supports nested associations. E.g:

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

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

There is no need for the solution given below. Refer to thisscreencast for more details.

不需要下面给出的解决方案。有关更多详细信息,请参阅截屏视频。

Original Answer

原答案

You are passing a has_many :throughassociation as a source for another has_many :throughassociation. I don't think it will work.

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

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

You have three approaches to solving this issue.

您可以通过三种方法来解决此问题。

1) Write an association extension

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

Now you can get the friends comments as follows:

现在你可以得到朋友的评论如下:

user.friends.comments

2) Add a method to the Userclass.

2) 在User类中添加一个方法。

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

Now you can get the friends comments as follows:

现在你可以得到朋友的评论如下:

user.friends_comments

3) If you want this to be even more efficient then:

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

Now you can get the friends comments as follows:

现在你可以得到朋友的评论如下:

user.friends_comments

All methods cache the results. If you want to reload the results do the following:

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

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

OR better still:

或者更好:

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

回答by Jarl

There is a plugin that solves your problem, take a look at this blog.

有一个插件可以解决您的问题,请查看此博客

You install the plugin with

你安装插件

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

回答by Andrew Culver

Although this didn't work in the past, it works fine in Rails 3.1 now.

虽然这在过去不起作用,但它现在在 Rails 3.1 中运行良好。