Can't figure out best way to display joined data in Rails 5 with has_many_through relationship

49 Views Asked by At

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

  1. Cinema 1
    • 12:30
    • 15:00
  2. 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

1

There are 1 best solutions below

4
On BEST ANSWER

You may need to add relationship to Run first

class Run < ApplicationRecord
  belongs_to :movie
  belongs_to :cinema
end

Then use includes and start the loop from runs.

For example:

@movie = Movie.where(... the condition ...).includes(:runs => :cinemas).first
@movie.runs.group_by(&:cinema_id).each do |movie_id, runs|
  <%= runs.first.cinema.name %>
  runs.each do |run|
    <%= run.time %>
  end
end

Note that

runs.group_by(&:cinema_id) 

is a syntax sugar of

runs.group_by{|run| run.cinema_id }

The usage example of group_by method:

(1..6).group_by {|i| i%3}   #=> {0=>[3, 6], 1=>[1, 4], 2=>[2, 5]}