我有一个可过滤的产品页面,使用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
。我明白为什么这样做呢;我不清楚如何收集结果,添加它们并显示计数。
最好从控制器动作本身设置总计数。如果我们可以通过数据库查询本身获取它,那么循环遍历每个产品以获得总变化计数是不好的。
def index
...
@total_variations = Variation.joins(:product).where(product: @products).count
end
count变量可以在视图中使用。
<%= @total_variations %> - variations
你可以在循环外保持一个运行计数,例如:
...
<% total_variations = 0 %>
<% @products.each do |p| %>
<% total_variations += p.variations.count %>
<%= total_variations %> - variations
<% end %>
您可以使用with_index
执行此操作,例如按照以下代码
...
<% @products.each.with_index(1) do |p, index| %>
<%= index %> - variations
<% end %>
...
或者如果您想从零开始,请遵循以下代码
...
<% @products.each_with_index do |p, index| %>
<%= index %> - variations
<% end %>
...
希望能帮助到你