2016-03-07 101 views
0

我在制作电影票务应用程序,其中有电影,每部电影都有很多放映时间。保存与现有模型的关联

这是我的电影类:

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

end 

和Showtime类

class Showtime < ActiveRecord::Base 
    belongs_to :movie 

end 

在我的欣欣形式我有以下领域

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

在我的欣欣控制器做我有以下创建方法

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 

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

回答

0

如果切换到movie_id应该工作,但我更喜欢使用options_for选择:

<%= 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 
+0

这样做的好处是什么? –

+0

只是个人喜好。我发现比查找collection_for_select的顺序或参数更容易记住。 select的选项可以采用一维数组,或者,如果要显示不同的值(名称而不是id,如上所示),则可以使用二维数组。我想,我不喜欢需要大量参数的方法。不管哪种方式都行得通。 – toddmetheny

0

由于showtime_params许可证:movie_id那你必须给到您的收藏领域名称:

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