John Sam John Sam - 1 month ago 9
Ruby Question

Rails, how to avoid the "N + 1" queries for the totals (count, size, counter_cache) in associations?

I have a these models:

class Children < ActiveRecord::Base
has_many :tickets
has_many :movies, through: :tickets
end


class Movie < ActiveRecord::Base
has_many :tickets
has_many :childrens, through: :tickets
belongs_to :cinema
end


class Ticket < ActiveRecord::Base
belongs_to :movie, counter_cache: true
belongs_to :children
end


class Cinema < ActiveRecord::Base
has_many :movies, dependent: :destroy
has_many :childrens, through: :movies
end


What I need now is in the page of "Cinemas" I wanna print the sum (count, size?) of the childrens just for the movies of that cinemas, so I wrote this:


  • in the cinemas_controller.rb:



@childrens = @cinema.childrens.uniq



  • in the cinemas/show.html.erb:



<% @childrens.each do |children| %><%= children.movies.size %><% end %>


but obviously I have bullet gem that alert me for Counter_cache and I don't know where to put this counter_cache because of different id for the movie.

And also without the counter_cache what I have is not what I want because I want a count for how many childrens in that cinema taking them from the tickets from many days in that cinema.

How to?

UPDATE

If in my view I use this code:

<% @childrens.each do |children| %>
<%= children.movies.where(cinema_id: @cinema.id).size %>
<% end %>


gem bullet don't say me anything and every works correctly.

But I have a question: this way of querying the database is more heavy because of the code in the views?

Answer

This might help you.

@childrens_count = @cinema.childrens.joins(:movies).group("movies.children_id").count.to_a