Forum: Ruby on Rails Real Dumb Newbie Q: Saving multiple data sets from one form

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
17d01ff4326c26911481c7a77283b343?d=identicon&s=25 esloane (Guest)
on 2005-12-07 00:05
(Received via mailing list)
Hi,
I have a couple of tables, Jobs and Addresses with a HABTM relationship
through Jobs_Addresses and I have a model and controller for both jobs
and addresses. What would be the best way to code a create method to
save the two data sets?  I tried;

  def create
     @job = Job.new(params[:job])
     @address = Address.new(params[:address])
     if @job.save && @address.save
       flash[:notice] = 'Job was successfully created.'
       redirect_to :action => 'list'
     else
       render :action => 'new'
     end
   end

Which resulted in;

  NoMethodError in Job#create

undefined method `address' for #<Job:0x3912190>


Request

Parameters: {"commit"=>"Save Job Data", "job"=>{"job_number"=>"1984",
"closed"=>"false", "job_phase_id"=>"1", "job_type_id"=>"1"},
"address"=>{"country"=>"Australia", "suburb"=>"Spanish Harlem",
"address_1"=>"Level 42", "address_2"=>"77, Sunset Strip",
"state"=>"Confused"}}

So all the data is there I just don't know how to split the save to two
tables.

Sorry it's such a dumb question. Help much appreciated
Kind Regards,
Eric.
71b46c4f6e9cfec742e18deeec6d2cd9?d=identicon&s=25 Joost Baaij (joost)
on 2005-12-08 17:39
def create
  @job = Job.new(params[:job])
  @address = Address.new(params[:address])
  @job.address << @address
  # Then save the objects
end

This could probably be rewritten using the .create method (which
instantiates an object and saves it right away).
This topic is locked and can not be replied to.