在Rails 5.1模板中显示pg_search的循环计数

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

我有一个可过滤的产品页面,使用pg_search宝石有很多变化,效果很好。我试着在结果显示中显示搜索结果的总数。我在下面看到的部分工作原理 - 它显示了变化的数量,但没有显示总数;它显示每个产品的计数。

products_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

产品/ index.html.erb

...
<% @products.each do |p| %>
    <%= p.variations.count %> - variations
<% end %>
...

它显示的屏幕截图

对于下面显示的结果,它循环显示2个产品,每个产品有1个变体,因此它将它们列为单独的而不是总计为总计数。应该展示的是2 - variations。我明白为什么这样做呢;我不清楚如何收集结果,添加它们并显示计数。

enter image description here

ruby-on-rails ruby-on-rails-5 pg-search
3个回答
1
投票

最好从控制器动作本身设置总计数。如果我们可以通过数据库查询本身获取它,那么循环遍历每个产品以获得总变化计数是不好的。

def index
  ...
  @total_variations = Variation.joins(:product).where(product: @products).count
end

count变量可以在视图中使用。

<%= @total_variations %> - variations

0
投票

你可以在循环外保持一个运行计数,例如:

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

0
投票

您可以使用with_index执行此操作,例如按照以下代码

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

或者如果您想从零开始,请遵循以下代码

...
<% @products.each_with_index do |p, index| %>
   <%= index %> - variations
<% end %>
...

希望能帮助到你

© www.soinside.com 2019 - 2024. All rights reserved.