2012-12-26 54 views
2

我有一些場景,我希望儘可能少的數據庫通過預先加載進行調用,但是我一直無法做到。在使用RABL和mongoid時減少數據庫調用

鑑於以下兩種情況,我如何改變我的RABL以儘可能少地打電話?


對象模型:

Posts 
-> belongs_to user 
-> has_many: Comments 
    -> Comment belongs_to user 
-> has_many: Tags 
    -> Tag belongs_to user 

Rabl的(這些將導致DB做許多個人電話)

node(:comments) do |p| 
    p.filtered_comments(@user) 
end 

child :tags do 
    attribute :text 
    child :users do 
    attribute :nickname 
    end 
end 

控制器QUERY

Post.includes(user, comments, tags)... 

POST。 RB

def filtered_comments 
    comments = self.comments.where(:blocked=>false).all 
    json = Rabl::Renderer.json(comments, 'comments/list', view_path: 'app/views') 
    JSON.parse(json).map do |c| 
     c['comment'] 
    end 
end 
+0

你有多少個查詢正在發生的日誌? –

+0

如果用戶不接受任何內容,如何將用戶傳遞給'filtered_comments'方法? –

回答

1

通常,控制器定義rabl迭代的對象,比如@user

所以在控制器中,我通常會很急切地加載關係,比如像這樣的權限和文章:@user = User.find(1).includes(:permissions, :articles),並用這樣的用戶對象進行響應:respond_with @user

然後,在Rabl的文件,我有這樣的:

# some_file.json.rabl 
object @user 
child :permissions do 
    attributes :name 
end 
node :first_article do |u| 
    u.articles.first 
end 

這個固定我的版本健談視圖文件。