【问题标题】:N+1 query with rails polymorphic association具有 Rails 多态关联的 N+1 查询
【发布时间】:2013-07-22 02:07:00
【问题描述】:

我有两个模型。

专辑

class Album < ActiveRecord::Base
    has_one :post, as: :post_module, dependent: :destroy
end

帖子(具有 title 属性)

class Post < ActiveRecord::Base
    belongs_to :post_module, polymorphic: true
end

这是我的模板

<% @albums.each do |album| %>
  <tr>
    <td>
      <%= link_to album.post.title, edit_admin_album_path(album) %>&nbsp;<br/>
    </td>
  </tr>
<% end %>

我尝试使用:includes:references 来避免N + 1 查询。

def index
    @albums = Album.includes(:post).references(:post).to_a
end

但似乎 N + 1 查询仍然存在。这有什么问题?

SQL (0.2ms)  SELECT `albums`.`id` AS t0_r0, `albums`.`product_num` AS t0_r1, `albums`.`created_at` AS t0_r2, `albums`.`updated_at` AS t0_r3, `posts`.`id` AS t1_r0, `posts`.`title` AS t1_r1, `posts`.`date` AS t1_r2, `posts`.`post_module_id` AS t1_r3, `posts`.`post_module_type` AS t1_r4, `posts`.`created_at` AS t1_r5, `posts`.`updated_at` AS t1_r6 FROM `albums` LEFT OUTER JOIN `posts` ON `posts`.`post_module_id` = `albums`.`id` AND `posts`.`post_module_type` = 'Album'
Post Load (0.3ms)  SELECT `posts`.* FROM `posts` WHERE `posts`.`post_module_id` = 18 AND `posts`.`post_module_type` = 'Album' ORDER BY `posts`.`id` ASC LIMIT 1
Post Load (0.2ms)  SELECT `posts`.* FROM `posts` WHERE `posts`.`post_module_id` = 20 AND `posts`.`post_module_type` = 'Album' ORDER BY `posts`.`id` ASC LIMIT 1
Post Load (0.2ms)  SELECT `posts`.* FROM `posts` WHERE `posts`.`post_module_id` = 21 AND `posts`.`post_module_type` = 'Album' ORDER BY `posts`.`id` ASC LIMIT 1
Post Load (0.2ms)  SELECT `posts`.* FROM `posts` WHERE `posts`.`post_module_id` = 22 AND `posts`.`post_module_type` = 'Album' ORDER BY `posts`.`id` ASC LIMIT 1
Post Load (0.1ms)  SELECT `posts`.* FROM `posts` WHERE `posts`.`post_module_id` = 23 AND `posts`.`post_module_type` = 'Album' ORDER BY `posts`.`id` ASC LIMIT 1

【问题讨论】:

  • 即使我不使用@album =Album.all 在每个循环中调用`album.post.title',似乎也会发生N + 1
  • 仅尝试 Album.includes(:post)
  • 它得到了相同的结果:(
  • 试试 Album.all(:include => :post)
  • 你能发帖吗,你的 def 索引有什么变化?

标签: mysql ruby-on-rails database performance


【解决方案1】:

您正在尝试在多态关联中进行预加载。

更多详情请参考以下网站

Polymorphic Association and Eager Loading Issues

请尝试

Album.all.includes(:post => :post_module)

【讨论】:

  • 它抛出错误 'Association named 'polymorphic' was not found' T T
【解决方案2】:

【讨论】:

猜你喜欢
  • 2017-07-20
  • 2015-10-24
  • 1970-01-01
  • 2015-03-26
  • 1970-01-01
  • 1970-01-01
  • 2015-10-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多