2013-05-28 47 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)