ruby on rails - Save both or neither model in controller -


i want save 2 models in 1 controller action, or save neither, , return validation errors.

is there better way this?

def update     @job = job.find(params[:id])     @location = @job.location      @job.assign_attributes(job_params)     @location.assign_attributes(location_params)     @job.save unless @job.valid? # gets validation errors     @location.save unless @location.valid? # gets validation errors      if @job.valid? && @location.valid?       @job.save       @location.save       flash[:success] = "changes saved."       redirect_to edit_job_path(@job)     else       render 'edit'      end   end 

new version:

def update   @job = job.find(params[:id])   @location = @job.location    begin     job.transaction       @job.assign_attributes(job_params)       @job.save!(job_params)       @location.assign_attributes(location_params)       @location.save!(location_params)     end     flash[:success] = "changes saved."     redirect_to edit_job_path(@job)   rescue activerecord::recordinvalid => invalid     render 'edit'   end end 

have @ active record nested attributes. using nested attributes, can save associated record attributes through parent.if parent record fails, associated records won't saved.!


Comments

Popular posts from this blog

IF statement in MySQL trigger -

c++ - What does MSC in "// appease MSC" comments mean? -

javascript - Blogger related post gadget image Resize s72-c [ Need Expert Help ] -