Forum: Ruby on Rails Saving or updating multiple models

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.
3a18f0e7810b93223a39bf00c9d403b5?d=identicon&s=25 Frodo Larik (Guest)
on 2006-01-09 23:10
(Received via mailing list)
Hello all,

I was wondering how one would create multiple models in one controller
action.

Consider the following models:

class Worker < ActiveRecord::Base
   belongs_to :person
   belongs_to :user
   validates_presence_of :person_id
end

class Person < ActiveRecord::Base
   has_many :workers
end

class Client < ActiveRecord::Base
   has_many :workers
end

class User < ActiveRecord::Base
   # several validations
end

and the following controller_code:

class WorkersController < ApplicationController
   def create
      @worker = Worker.new(params[:worker])
      @worker.person = Person.new(params[:person])
      @worker.user = User.new(params[:user]) if @worker.is_contact

       if @worker.save
          # success
       else
          # failure
       end
   end
end


The problem as far as I can see here is, that the @worker model is
tried to be saved, without saving the children first.

Another thing is, when I do things like:

@worker.person.save
@worker.save

than the @worker doesn't get saved because it doesn't know the
@worker.person_id .

How to save multiple models from one controller respecting callbacks (
before_save, before_create, etc...) ?

--
Sincerely,

Frodo Larik
This topic is locked and can not be replied to.