John Sam John Sam - 10 months ago 64
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

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

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

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

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?


If in my view I use this code:

<% @childrens.each do |children| %>
<%= children.movies.where(cinema_id: %>
<% 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 Source

This might help you.

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