1 Form > 2 Models > 2nd Model Requres 1st Model ID

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"

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.

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