Hey Everyone, So I have one form that submits information to create 2 models (A, B). I need the ID of model A to be inserted into model B. But the ID isn''t created until it hits the database (auto_increment). But if for some reason either item cannot be created or saved I want to abort the whole operation. Whats the best method to do this ? thanks.
google "rails 1 form 2 models" -- Posted via http://www.ruby-forum.com/.
I can handle building two models from 1 form. It''s getting the id from the first saved model and inserting it in the second and rolling back the whole transaction if anything goes wrong that is the problem. On Aug 28, 9:43 am, Ar Chron <rails-mailing-l...-ARtvInVfO7ksV2N9l4h3zg@public.gmane.org> wrote:> google "rails 1 form 2 models" > -- > Posted viahttp://www.ruby-forum.com/.
Hi brianp
From what I understood you have to put the whole thing in a
transaction like
ActiveRecord::Base.transaction do
save first model object
save second model object
end
Sijo
--
Posted via http://www.ruby-forum.com/.
brianp
2009-Aug-31 06:38 UTC
Re: 1 Form > 2 Models > 2nd Model Requres 1st Model ID *Solved*
Thanks everyone for your suggestions.
This is what I came up with I was looking for some feedback. It works
fine but I figure I might be doing something long winded. This is my
first go at an actual railsApp other then book demos. Any feedback
would be nice!
// new.html.erb
<h1>New word</h1>
<%= error_messages_for :word, :definition %>
<% form_for(@word) do |f| %>
<p>
<%= f.label :word %><br />
<%= f.text_field :word %>
</p>
<p>
<%= f.label :was_created_by %><br />
<%= f.check_box :was_created_by %>
</p>
<% fields_for(:definition, @definition) do |i| %>
<p>
<%= i.label :definition %><br />
<%= i.text_area :definition %>
</p>
<p>
<%= i.label :word_type %><br />
<%= i.text_field :word_type %>
</p>
<p>
<%= i.label :pronounciation %><br />
<%= i.text_field :pronounciation %>
</p>
<p>
<%= i.label :origin %><br />
<%= i.text_area :origin %>
</p>
<p>
<%= i.label :is_profain %><br />
<%= i.check_box :is_profain %>
</p>
<% end %>
<p>
<%= submit_tag ''Create'' %>
</p>
<% end %>
<%= link_to ''Back'', words_path %>
// words_controller.rb
def create
@client_ip = request.remote_ip
begin
ActiveRecord::Base.transaction do
@word = Word.new(params[:word].merge(:ip_address =>
@client_ip, :user_id => ''1''))
@word.save
@definition = Definition.new(params[:definition].merge
(:ip_address => @client_ip,
:user_id
=> ''1'',
:word_id
=> @word.id,
:status
=> ''published''))
@definition.save
end
rescue ActiveRecord::RecordInvalid => invalid
flash[:notice] = ''Word was not created''
render :action => "new"
end
redirect_to(@word)
end
On Aug 29, 4:16 am, Sijo Kg
<rails-mailing-l...-ARtvInVfO7ksV2N9l4h3zg@public.gmane.org>
wrote:> Hi brianp
> From what I understood you have to put the whole thing in a
> transaction like
>
> ActiveRecord::Base.transaction do
> save first model object
> save second model object
> end
>
> Sijo
> --
> Posted viahttp://www.ruby-forum.com/.