如何防止数组中产生附加条件的 n+1 问题?

问题描述 投票:0回答:1

在包含查询的数组上使用条件时,我面临 n+1 问题。

以下是下表:

rems
|id| |name|
 1  aaa
 2  bbb

rem_correlatives
|id| |rem_id| |name|  |deleted|  |pending_tr|
 1     1       qqqq1      0          0
 2     1       qqqq2      0          1 
 3     1       qqqq1      1          0
 4     1       qqqq2      1          1
 5     1       qqqq1      0          0
 6     1       qqqq2      0          1 
 7     1       qqqq1      1          0
 8     1       qqqq2      1          1
 9     2       qqqq1      0          0
 10    2       qqqq2      0          1 
 11    2       qqqq1      1          0
 12    2       qqqq2      1          1
 13    2       qqqq1      0          0
 14    2       qqqq2      0          1 
 15    2       qqqq1      1          0
 16    2       qqqq2      1          1

以下是型号:

 class Rem < ApplicationRecord
    has_many :rem_correlatives
 end

 class RemCorrelative < ApplicationRecord
    belongs_to :rem
 end

这是位于 /app/controllers/rems_controller.rb 的名为 rems_controller.rb 的控制器

 def index
    @list_array = Rem.includes(:rem_correlatives).all
 end

这是位置 /app/views/rems/index.html.erb 的索引视图

 <% @list_array.each do |array| %>
      <% array.name %>
      <% @check_result = array.rem_correlatives.where("deleted=0 AND pending_tr= 1)%>
        <% if @check_result.present? %>
           No
        <% else %>
           Yes
        <% end %>
      <% end %>
   
 <% end%>

我尝试了这个解决方法代码,使用列ending_tr = 1和deleted = 0显示数据数组,但似乎不是一个好的做法。

 <% @list_array.each do |array| %>
      <% array.name %>
      <% array.rem_correlatives.each do |rem_correlative|%>
        <!--  Create condition pending_tr=1 AND deleted=0  -->
        <% if rem_correlative.pending_tr == 1 && rem_correlative.deleted == 0%>
           <% @check_condition = "No" %>
        <% else %>
           <% @check_condition = "Yes"%>
        <% end %>
      <% end %>
      <!--  Check results from array if the word yes exists --> 
      <% if @check_condition.include?("Yes") %>
         si 
      <% else %>
        no
      <% end %>          
 <% end%>

这是使用解决方法代码时的后端结果,它有效并且不显示 n+1 问题。

如何防止数组中生成附加条件作为好代码的 n+1 问题?

ruby-on-rails ruby ruby-on-rails-4 eager-loading
1个回答
0
投票

我会在模型中创建一个与范围的专用关联。

# in app/models/rem.rb
has_many :pending_rem_correlatives,
  class_name: 'RemCorrelative', -> { where(deleted: false, pending_tr: true) }

然后在控制器和视图中使用此关联。

# in the controller
@rems = Rem.includes(:pending_rem_correlatives).all

# in the view
<% @rems.each do |rem| %>
  <%= rem.name %>

  <% if rem.pending_rem_correlatives.any? %>
    No such rem correlatives
  <% else %>
    There are matching rem correlatives
  <% end %>
<% end %>
© www.soinside.com 2019 - 2024. All rights reserved.