2013-05-28 42 views
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问题。

我该如何进行查询?

回答

1

includes方法只能帮助加载,它不会帮助您获取propper记录。

你需要的可能是这样的:

# get all posts with comments made by the user 
posts = Post.where(:comments => { :user_id => params[:user_id] }) 
# fetch the categories for those posts 
@categories = Category.find(posts.map(&:category_id).uniq)