Ruby on rails 在Rails 5.1模板中显示pg_搜索中的循环计数

Ruby on rails 在Rails 5.1模板中显示pg_搜索中的循环计数,ruby-on-rails,ruby-on-rails-5,pg-search,Ruby On Rails,Ruby On Rails 5,Pg Search,我有一个可过滤的产品页面,有很多使用gem的变体,效果很好。我正在尝试显示搜索结果的总数,作为我的结果显示的一部分。正如您在下面看到的,我所做的部分工作是有效的——它显示了变化的数量,但没有显示总数量;它显示了每种产品的数量 产品\u controller.rb def index @products = if params[:query] @albums = Album.where(name: params[:query])

我有一个可过滤的产品页面,有很多使用gem的变体,效果很好。我正在尝试显示搜索结果的总数,作为我的结果显示的一部分。正如您在下面看到的,我所做的部分工作是有效的——它显示了变化的数量,但没有显示总数量;它显示了每种产品的数量

产品\u controller.rb

  def index
    @products =
        if params[:query]
          @albums = Album.where(name: params[:query])
          Product.search_for(params[:query])
        else
          # @albums - products is the default image gallery for all products index page
          @albums = Album.where(name: 'products')
          Product.order(:name)
        end
  end
...
<% @products.each do |p| %>
    <%= p.variations.count %> - variations
<% end %>
...
products/index.html.erb

  def index
    @products =
        if params[:query]
          @albums = Album.where(name: params[:query])
          Product.search_for(params[:query])
        else
          # @albums - products is the default image gallery for all products index page
          @albums = Album.where(name: 'products')
          Product.order(:name)
        end
  end
...
<% @products.each do |p| %>
    <%= p.variations.count %> - variations
<% end %>
...
。。。
-变化
...
显示内容的屏幕截图

对于下面所示的结果,它循环遍历2个产品,每个产品有1个变体,因此它将它们单独列出,而不是作为总数相加。它应该显示的是
2-变体
。我确实理解它为什么这样做;我只是不清楚如何收集结果,将它们相加并显示计数


你能在循环之外保持跑步计数吗,例如:

...
<% total_variations = 0 %>
<% @products.each do |p| %>
    <% total_variations += p.variations.count %>
    <%= total_variations %> - variations
<% end %>
。。。
-变化

您只需使用
和_index
即可完成此操作,如下代码所示

...
<% @products.each.with_index(1) do |p, index| %>
   <%= index %> - variations
<% end %>
...
...
<% @products.each_with_index do |p, index| %>
   <%= index %> - variations
<% end %>
...
。。。
-变化
...
或者,如果您想从零开始,则遵循以下代码

...
<% @products.each.with_index(1) do |p, index| %>
   <%= index %> - variations
<% end %>
...
...
<% @products.each_with_index do |p, index| %>
   <%= index %> - variations
<% end %>
...
。。。
-变化
...

希望有帮助

设置控制器操作本身的总计数会很好。如果我们可以通过DB查询本身获得总的变化计数,那么循环每个产品以获得总的变化计数是不好的

def index
  ...
  @total_variations = Variation.joins(:product).where(product: @products).count
end
可以在视图中使用count变量

<%= @total_variations %> - variations
-变体