Count has_many relationships I have 3 models: Import, Product, Values.
An import has_many products.
A product has_many values.

I want to find the product with the highest values count and the sum of all values for all those products. My current method is very expensive.

@import = Import.find(params[:id])
@products = @import.products
@max_product = @products.max_by{|product| product.values.count}
@values_count = @products.sum{|product| product.values.count}


How can I make this more efficient ?
You can make use ":counter_cache", it finds the number of belonging objects more efficient.

class Book &lt; ApplicationRecord
  belongs_to :author, counter_cache: true
end
class Author &lt; ApplicationRecord
  has_many :books
end


Asking for the value of @author.books.size requires making a call to the database to perform a COUNT(*) query. To avoid this call, you can add a counter cache, with this declaration, Rails will keep the cache value up to date, and then return that value in response to the size method.

Reference : http://guides.rubyonrails.org/association_basics.html