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 L.