保存与现有模型的关联

Saving association with existing model

我正在构建一个电影票务应用程序,其中我有电影并且每部电影都有很多放映时间。

这是我的电影class:

class Movie < ActiveRecord::Base
  has_many :showtimes, dependent: :destroy

end

和放映时间 class

class Showtime < ActiveRecord::Base
  belongs_to :movie

end

在我的放映时间表单中,我有以下字段

<%= f.collection_select :movie, Movie.all, :id, :title %>

在我的 showtime 控制器中是否有以下创建方法

  def create
    @showtime = Showtime.new(showtime_params)
    if @showtime.save
      redirect_to @showtime, notice: 'Showtime was successfully created.'
    else
      render :new
    end
  end

  def showtime_params
    params.require(:showtime).permit(:movie_id, :start_time)
  end

这是保存关联的正确方法吗?

由于 showtime_params 允许:movie_id 那就是您必须为 collection 字段指定的名称:

<%= f.collection_select :movie_id, Movie.all, :id, :title %>

如果您更改为 movie_id 应该可以,但我更喜欢使用 options_for select:

<%= f.select :movie_id, options_for_select(Movie.choices) %>

在你的 movie.rb

def self.choices
   options = []
   Movie.find_each do |movie|
     options << [movie.title, movie.id]
   end
   options
end