【发布时间】:2012-12-11 18:53:42
【问题描述】:
在一些场景中,我想通过预先加载尽可能少地调用数据库,但我一直没能做好。
鉴于以下 2 种情况,我如何更改我的 RABL 以尽可能少地拨打电话?
对象模型:
Posts
-> belongs_to user
-> has_many: Comments
-> Comment belongs_to user
-> has_many: Tags
-> Tag belongs_to user
RABL(这两者都会导致数据库进行许多单独的调用)
node(:comments) do |p|
p.filtered_comments(@user)
end
child :tags do
attribute :text
child :users do
attribute :nickname
end
end
控制器查询
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
【问题讨论】:
-
你有关于发生了多少查询的日志吗?
-
如果
filtered_comments方法不接受,你如何将用户传递给它?
标签: ruby-on-rails json mongoid rabl object-object-mapping