I have a filterable products page that has_many variations using the pg_search gem and it works well. I am tryin to show the total count of the search results as part of my results display. What I've done as you can see below partially works--it shows the count of variations, but doesn't show total count; its showing the count on a per product basis.
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
products/index.html.erb
...
<% @products.each do |p| %>
<%= p.variations.count %> - variations
<% end %>
...
Screenshot of what it displays
For the result shown below, it is looping through 2 products, each has 1 variation, so its listing them as separate instead of adding up as a total count. What it should display is 2 - variations
. I do understand why its doing it this way; I am just unclear how to collect the results, add them up and display the count.
It would be good to set the total count from controller action itself. Looping through each product to get total variations count is not good if we can get it via DB query itself.
def index
...
@total_variations = Variation.joins(:product).where(product: @products).count
end
The count variable can be used in the view.
<%= @total_variations %> - variations