check_box_tag包含n + 1个查询

时间:2018-01-06 18:34:36

标签: sql ruby-on-rails ruby

文章所属的故事列表中的以下行 - 在编辑文章页面上,允许我将文章分配给故事 - 作品但产生n + 1查询(我认为)。

造成问题的位是@article.stories.include?(s),它检查文章是否已属于某个故事:

<%= check_box_tag "article[story_ids][]", s.id, @article.stories.include?(s) %>

Log说Rails正在进行50多个查询(所有故事)因为这一点;示例中的article_id = 266:

Story Exists (0.4ms)  SELECT  1 AS one FROM "stories" INNER JOIN "articles_stories" ON "stories"."id" = "articles_stories"."story_id" WHERE "articles_stories"."article_id" = $1 AND "stories"."id" = $2 LIMIT 1  [["article_id", 266], ["id", 6]]
Story Exists (0.3ms)  SELECT  1 AS one FROM "stories" INNER JOIN "articles_stories" ON "stories"."id" = "articles_stories"."story_id" WHERE "articles_stories"."article_id" = $1 AND "stories"."id" = $2 LIMIT 1  [["article_id", 266], ["id", 51]]
Story Exists (0.3ms)  SELECT  1 AS one FROM "stories" INNER JOIN "articles_stories" ON "stories"."id" = "articles_stories"."story_id" WHERE "articles_stories"."article_id" = $1 AND "stories"."id" = $2 LIMIT 1  [["article_id", 266], ["id", 41]]
Etc., etc.

article_id = 266所属的实际故事数是...... 2:

 select * from articles_stories where article_id = 266;

 article_id | story_id 
 ------------+----------
    266 |       35
    266 |        5

 (2 rows)

我该如何解决?

更新:DB,整块&amp;控制器

Article.rb:

has_and_belongs_to_many :stories

Story.rb:

has_and_belongs_to_many :articles

check_box_tag所输入的整个代码块按照您可以分配给文章的类别打印故事列表:

<% @stories.group_by(&:category).sort_by{|c, stories| c.category}.each do |c, stories| %>
  <div class="admin-stories-in-categories">
    <strong><%= c.category unless c.nil? %></strong>
      <ul>
        <% for s in stories %>
          <li>
            <%= check_box_tag "article[story_ids][]", s.id, @article.stories.include?(s) %>
            <%= s.story %>
          </li>
        <% end %>
      </ul>
  </div>
<% end %>

在articles_controller.rb中:

@stories = Story.all.includes(:category).order(:story)

解答:

AbM的回答使得N + 1个查询消失,而是返回一个查询:

Returns `(0.8ms)  SELECT "stories"."id" FROM "stories" INNER JOIN "articles_stories" ON "stories"."id" = "articles_stories"."story_id" WHERE "articles_stories"."article_id" = $1  [["article_id", 266]]`

2 个答案:

答案 0 :(得分:1)

我们需要您的数据库架构和您在控制器中使用的查询(如果有的话) - 但您可能只需执行Article.includes(:stories).find(params[:id])

之类的操作

我建议将Bullet插入开发堆栈中。

https://github.com/flyerhzm/bullet

答案 1 :(得分:1)

非常感谢,因为如果没有加载关系,here

,活动记录关系中的include?方法会在sql中执行EXIST操作

尝试将文章故事存储在变量中:

<% article_stories_ids = @article.stories.pluck(:id) %>
<% @stories.group_by(&:category).sort_by{|c, stories| c.category}.each do |c, stories| %>
  <div class="admin-stories-in-categories">
    <strong><%= c.category unless c.nil? %></strong>
      <ul>
        <% stories.each do |s| %>
          <li>
            <%= check_box_tag "article[story_ids][]", s.id, article_stories_ids.include?(s.id) %>
            <%= s.story %>
          </li>
        <% end %>
      </ul>
  </div>
<% end %>