无法找出在具有 has_many_through 关系的 Rails 5 中显示连接数据的最佳方式

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

我有 3 个模型:Cinema、Movie 和 运行。 Cinema 和 Movie 通过 运行 建立了关系,例如:

class Movie < ApplicationRecord
  has_many :cinemas, -> { distinct }, through: :runs
  has_many :runs
end

我正在尝试显示特定电影的电影院列表以及每个电影院的放映列表:

电影 1

  1. 电影院 1
    • 12:30
    • 15:00
  2. 电影院 2
    • 15:30
    • 16:00

我不知道如何减少数据库调用。现在我正在为每个电影院打电话,所以它与数量或电影院成正比。我觉得不对

@movie.cinemas.each do |cinema|
   cinema.runs.where(movie_id: @movie.id).each do |run|
      = run.time

需要帮助

您可能需要先添加与 Run 的关系

class Run < ApplicationRecord
  belongs_to :movie
  belongs_to :cinema
end

然后使用includes并从runs开始循环。

例如:

@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

请注意

runs.group_by(&:cinema_id) 

的语法糖
runs.group_by{|run| run.cinema_id }

group_by方法的使用示例:

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