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

Philip Hallstrom
Wed, 29 Dec 2010 19:41:43 -0000

On Dec 29, 2010, at 11:33 AM, Jim Burgess wrote:

> Hi,
>
> I''m trying to understand some code in a book I''m reading
and was hoping
> someone could tell me if I have understood it correctly.
>
> There are two models, an employee model and a department model. A
> department has_many :employees and an employee belongs_to :department.
>
> Here''s a snippet of code from the form to edit an existing
employee:
>
> <% fields_for( @employee.department) do |department_f| %>
>
>    <%= department_f.label :name,"Department name" %><br
/>
>    <%= department_f.text_field :name %>
>
> <% end %>
>
> The form is submitted to the update action of
''employees_controller.rb'',
> where there is the following code:
>
> if @employee.update_attributes(params[:employee]) &&
> @employee.department.update_attributes(params[:department])
>  ... employee successfully updated ...
> end
>
> My question is about the line
> "@employee.department.update_attributes(params[:department])"
>
> Is it correct to say that this code updates the attributes (in this case
> "name") of the Department object that is linked (via the
"has_many" and
> "belongs_to" relationship) to the Employee object currently being
> edited?

Yes.  And it only does this if the update to @employee was successful first.

-philip