Auto generate models on creation of other models in Ruby on Rails

I have a model called Video that has many statuses. I want to create a status of each kind and add it to @video.statuses in the def create of VideosController.

In VideosController, I have:

def create     @video = Video.new(params[:video])     Kind.all.each do |f|       @video.statuses.new(:kind =>f, :kind_id=>f.id,:comment =>"", :time_comp => nil, :completed =>false, :video_id =>@video.id)

I think you probably want @video.statuses.create( .. ) so that the status objects will be saved. See the Rails Guide on ActiveRecord Associations for more detail.

Colin

You don't need ":video_id => @video.id". Replace this line with that: @video.statuses.build(:kind =>f, :kind_id=>f.id,:comment =>"", :time_comp => nil, :completed =>false) build is an alias to new, you can look here[0]

Then when you call @video.save, all statuses will create too, with @video.id .

In your code @video is not saved when you call to statuses.new, then @ video.id is nil, that's why of your error

[0]

Carlos is right, my suggestion to use create will not work as the video has not been saved yet.

Colin