Count has_many relationships
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