Friday, May 10, 2013

Re: [Rails] Auto generate models on creation of other models in Ruby on Rails

On Fri, May 10, 2013 at 5:09 AM, Colin Law <clanlaw@googlemail.com> wrote:
On 9 May 2013 22:41, Jessica Lu <loppilop@gmail.com> wrote:
> 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)

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

 



--
Matt's 

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate