1

我有以下型号

class Forum < ActiveRecord::Base
  has_many :topics
end

class Topic < ActiveRecord::Base
  belongs_to :forum
  has_many :posts
end

class Posts < ActiveRecord::Base
  belongs_to :topic
  belongs_to :user
end

我想加入这些关联(在主题和帖子上都有一些条件),所以我做了Topic.joins(:forum, :posts).where(some condition),但我想访问所有三个表中的属性。我怎样才能做到这一点?

4

1 回答 1

0

您可以像这样进行多重连接。所有三个表都可用,您只需在 wheres 中指定。

Topic.joins(:forum, :posts).where('topics.foo' => 'bar').where('posts.whizz' => 'bang)

两个警告是,这是一个多重内部连接,因此该主题需要同时拥有论坛和帖子才能显示出来,并且 where 是 anded 在一起的。对于 where's 中的外部连接或“或”逻辑,您将不得不变得更加出色。但是您可以为 .joins 和 .where 编写 sql 来实现这一点。使用 .includes 而不是 .joins 是获得外连接行为的另一种方法——但当然你可能会加载很多记录。

为了澄清下面的评论,并在另一个用户建议的语法中显示改进的(更多 rails-y)语法:

topics = Topic.joins(:forum, :posts).where(topic: {foo: 'bar'}).where(posts: {whizz: 'bang'})
topics.each do |t|
   puts "Topic #{t.name} has these posts:"
   t.posts.each do |p|
     puts p.text
   end
end
于 2013-11-05T21:18:44.343 回答