2016-03-07 70 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 %>