是否有可能有多重 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

这看起来很棒,并且是有道理的,但不是为我工作。这是错误我得到了在相关部分,当我试着接一个用户的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)))

当我只是输入的用户。朋友,其工作,这是查询执行:
: SELECT "users".* FROM "users" INNER JOIN "friendships" ON "users".id = "friendships".friend_id WHERE (("friendships".user_id = 1) AND ((status = 2)))

使它看来似乎是完全忘记了原始 has_many 通过友好关系,然后是不恰当试图使用的用户类别作为参加表。

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

有帮助吗?

解决方案

修改

3.1的Rails支持嵌套关联。 E.g:

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)

其他提示

有是解决你的问题的一个插件,看一看的此博客

您安装插件与

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

虽然这并没有在过去的工作,它工作在Rails的3.1现在很好。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top