【问题标题】:Can't figure out best way to display joined data in Rails 5 with has_many_through relationship无法找出在具有 has_many_through 关系的 Rails 5 中显示连接数据的最佳方式
【发布时间】:2017-05-07 04:56:48
【问题描述】:

我有 3 个模型:Cinema、Movie 和 Run。 Cinema 和 Movie 通过 Run 建立了关系,如下所示:

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

需要帮助

【问题讨论】:

    标签: mysql ruby-on-rails ruby-on-rails-5 has-many-through jointable


    【解决方案1】:

    您可能需要先添加与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]}
    

    【讨论】:

    • 但是电影院列表呢?
    • 你可以使用runs.first.cinema
    • 对不起,我打错了runs.first.movie
    • 谢谢,但只有当我将 @movie.runs.group_by(&:movie_id) 更改为 @movie.runs.group_by(&:cinema_id) 你能解释一下“(&:cinema_id)”中的“&”是什么意思吗?
    猜你喜欢
    • 1970-01-01
    • 2017-02-21
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 2012-11-17
    • 1970-01-01
    • 2012-12-09
    • 1970-01-01
    相关资源
    最近更新 更多