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)
end
respond_to do |format|
if @video.save
format.html { redirect_to @video, notice: ‘Video was
successfully created.’ }
format.json { render json: @video, status: :created, location:
@video }
else
format.html { render action: “new” }
format.json { render json: @video.errors, status:
:unprocessable_entity }
end
end
end

However, this returns an error that says that the video could not be
saved
because the Statuses were invalid. The only validation in my entire
project
is in status and it merely checks that there is a video_id. I’m very
confused why I’m getting this error and would appreciate any help!

On 9 May 2013 22:41, Jessica Lu [email protected] wrote:

: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

On Fri, May 10, 2013 at 5:09 AM, Colin L. [email protected]
wrote:

  @video.statuses.new(:kind =>f, :kind_id=>f.id,:comment =>"",

:time_comp => nil, :completed =>false, :video_id =>@video.id)

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]


Matt’s

On 10 May 2013 11:36, Carlos M. [email protected] wrote:

@video = Video.new(params[:video])

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

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

Colin