to_json:包含在活动记录上需要数据库

时间:2011-01-10 04:38:02

标签: ruby-on-rails

我想生成一个具有一级关联的json字符串:

@lines = Line.joins(:mems)\
             .where("     lines.document_id = ?
                      AND lines.text <> 'root'
                      AND mems.review_after < ?", params[:id], Time.now())\
             .to_json :include => :mems

我的开发日志如下:

  Line Load (0.4ms)  SELECT `lines`.* FROM `lines` INNER JOIN `mems` ON `mems`.`line_id` = `lines`.`id` WHERE ( lines.document_id = '30'
 AND lines.text <> 'root'
 AND mems.review_after < '2011-01-10 04:14:59')
  Mem Load (0.2ms)  SELECT `mems`.* FROM `mems` WHERE (`mems`.line_id = 49)
  Mem Load (0.3ms)  SELECT `mems`.* FROM `mems` WHERE (`mems`.line_id = 50)
  Mem Load (0.2ms)  SELECT `mems`.* FROM `mems` WHERE (`mems`.line_id = 51)
  Mem Load (0.3ms)  SELECT `mems`.* FROM `mems` WHERE (`mems`.line_id = 52)
  Tag Load (0.1ms)  SELECT `tags`.* FROM `tags` WHERE (`tags`.`id` = 8) LIMIT 1
Rendered documents/review.erb within layouts/application (11.3ms)

如您所见,ActiveRecord对象使用内部联接生成单个查询。但是,to_json方法会为每个Line记录单独查询关联的模型。

有没有办法在不编写自定义序列化方法的情况下避免这些重复查询?

1 个答案:

答案 0 :(得分:1)

这是因为:include 渴望从数据库加载相关对象,您需要在原始查询中使用它。

解决方案很简单:只需使用includes

@lines = Line.includes(:mems)\
         .where("lines.document_id = ?
                 AND lines.text <> 'root'
                 AND mems.review_after < ?", params[:id], Time.now())\
         .to_json :include => :mems