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

Philip Hallstrom
Wed, 29 Dec 2010 23:48:21 -0000

On Dec 29, 2010, at 12:57 PM, Jim Burgess wrote:

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

Still... the code above is not "throwing an error".  It''s
just processing an if/else flow.

Look at update_attributes! to see what I''m talking about.

http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update_attributes%21

I only bring it up because Rails/Ruby *can* throw errors and raise exceptions
(which are themselves different) so it can get confusing if you play loose with
the terminology :-)