I have models and their association like,
Video 1: -------- n: Script
When users newly create a Video, I want it to create the very first
Script entry together.
I have put
@script = Script.new(:video_id => @video.id, :startp => 0, :text =>
'ToDo: ')
in Video controller, 'new' action, but it doesn't work (:startp value is
determined for the first one).
How can I create a Script entity together with Video?
Also, if possible, I want that first Script entry to be undestroyable.
Do you think I can do it?
Thanks in advance,
soichi
--
Posted via http://www.ruby-forum.com/.
I will try after_create.
I have put
after_create :create_first_script
def create_first_script
@video = Video.new(params[:video])
@script = Script.new(:video_id => @video.id, :startp => 0, :text =>
'ToDo: ')
end
in video.rb.
But I need to pass params[:video] somehow...
/videos/_form.html.erb (generated by scaffold) should do it, correct?
<%= form_for(@video) do |f| %>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :url %><br />
<%= f.text_field :url %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
I am not sure how to pass the video object from here.
Could anyone give me tips?
> You have to first save the @video before accessing the id, that is when
> the
> after_create or after_save is triggered.
> In your Video class, the after save has access to the @video instance
> through the self keyword (self.id in your case).
>
I need to clarify this point.
When videos_controller.rb calls for 'create' action, a new instance gets
persisted, correct?
When doing so, 'after_create' is called as well. It seems to me that
when 'after_create' is called, the new video instance is already
created. Please correct me, if I'm wrong.
I tried this. but no good ( I knew it! )
after_create :create_first_script
def create_first_script
@script = Script.new(:video_id => self.id, :startp => 0, :text =>
'ToDo: ')
end
Calling the create action in the controller does not create it in the
database, it is the call of 'save' within the create action that saves
it to the database. The after_save callback will be called from
within save, after it is saved to the db and then the id will be
valid.
>
> I tried this. but no good ( I knew it! )
>
> after_create :create_first_script
>
> def create_first_script
> @script = Script.new(:video_id => self.id, :startp => 0, :text =>
> 'ToDo: ')
> end
What do you think that code does? It creates a new object in memory,
but you have not saved it to the database, so after the method is
called your new object is immediately lost.
Colin
after_save :create_first_script
private
def create_first_script
@script = Script.new(:video_id => self.id, :startp => 0, :text =>
'ToDo: ')
@script.save
end