带有rails多态关联的N + 1查询

时间:2013-07-23 06:23:17

标签: mysql ruby-on-rails database performance

我有两个模特。

相册

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

发布(具有标题属性)

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

2 个答案:

答案 0 :(得分:1)

您正在尝试以多态关联方式加载。

请参阅以下网站了解更多详情

Polymorphic Association and Eager Loading Issues

请尝试

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

答案 1 :(得分:0)