Re: Re: Help needed understanding "fields_for" and resultant controller code

Jim Burgess
Wed, 29 Dec 2010 20:57:02 -0000

> No technical reason (as this is an update, not a create), but logically
> it would make sense that you''d want to update them in that order.

Cool. That was exactly the conclusion I''d drawn.

>> won''t rails throw an error and re-render the
''edit'' view if validation
>> for either @employee or @employee.department fails?

> Nope.  update_attributes simply returns true/false depending on whether
> or not it succeeded.  There are ways to make it raise an error, but your
> code isn''t doing that.

Yeah, sorry, I guess I didn''t include enough code with my original
question.
I''m (the book is) using the scaffold generator to create both
''employee''
and ''department'' resources. The complete update method
attempts to
update the attributes of @employee and @employee.department. If this
doesn''t work (as validation has failed, for example) it re-renders the
action ''edit''.

def update
  @employee = Employee.find(params[:id])
  respond_to do |format|
  if @employee.update_attributes(params[:employee]) &&
@employee.department.update_attributes(params[:department])
    format.html { redirect_to(@employee, :notice => ''Employee was
successfully updated.'') }
    format.xml  { head :ok }
  else
    @departments = Department.find(:all)
    format.html { render :action => "edit" }
    format.xml  { render :xml => @employee.errors, :status =>
:unprocessable_entity }
    end
  end
end

Thanks very much for your help.