1
预先加载我有4种型号:与动态条件
class Category < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :category
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :user
end
class User < ActiveRecord::Base
has_many :comments
end
我需要获取所有与某个用户提出的意见文章的类别。 我生成一个包含所有类别和帖子的json,但不包含评论。
我使用的查询:
@categories = Category.includes(:posts => :comments).where(:comments => { :user_id => params[:user_id] })
我使用Rabl的:
collection @categories
attributes ...
child :posts do
attributes ...
end
但是,这让所有的评论。 如果我使用连接而不是包含,我会遇到n + 1问题。
我该如何进行查询?