I have 3 models: Cinema, Movie and Run. Cinema and Movie has a relationship through Run, like so:
class Movie < ApplicationRecord
has_many :cinemas, -> { distinct }, through: :runs
has_many :runs
end
I'm trying to display list of cinemas of certain movie with list of runs for each cinema:
Movie 1
- Cinema 1
- 12:30
- 15:00
- Cinema 2
- 15:30
- 16:00
I can't figure out how to reduce database calls. Right now i'm making a call for each cinema, so its proportional for number or cinemas. Doesn't seems right to me
@movie.cinemas.each do |cinema|
cinema.runs.where(movie_id: @movie.id).each do |run|
= run.time
Need help with this
You may need to add relationship to
Run
firstThen use
includes
and start the loop fromruns
.For example:
Note that
is a syntax sugar of
The usage example of group_by method: