# Nested models, mass assignment problem

**URL:** <https://www.ruby-forum.com/t/nested-models-mass-assignment-problem/132110>\
**Category:** Rails\
**Created:** [March 17, 2008, 4:14am UTC](https://www.ruby-forum.com/t/nested-models-mass-assignment-problem/132110 "2008-03-17T04:14:49Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![jtslade](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/7ba0ec/32.png) [@jtslade](https://www.ruby-forum.com/u/jtslade)\
**Post date:** [March 17, 2008, 4:14am UTC](https://www.ruby-forum.com/t/nested-models-mass-assignment-problem/132110/1 "2008-03-17T04:14:49Z")

</div>

Thank you in advance.

I am trying to use mass assignment for nested models in my view. The  
first nested level works (thanks to a Railscast).

i.e. Driver.cars\_attributes=\>[{no=\>…},{make=\>…}] works but the  
second level don’t. I am trying to have, Driver.cars\_attribute=\>[{…},  
{…},{photo\_attributes=\>[{uploaded\_data=\>’…’}]}].

Right now photo\_attributes is empty when the form is submitted (i.e.  
"photo\_attributes=\>[]).

Parameters: {“commit”=\>“Create”,  
“authenticity\_token”=\>“e81dcdc38c224a032de31fa005afbe32”,  
“action”=\>“create”, “controller”=\>“drivers”,  
“driver”=\>{“occupation”=\>“Gamer”, “biography”=\>"",  
“car\_attributes”=\>[{“number”=\>“5”, “make”=\>“Kong”,  
“photo\_attributes”=\>[], “model”=\>“Buster”}], “nickname”=\>“JRTong”,  
“birthdate(1i)”=\>“1960”, “birthdate(2i)”=\>“3”, “birthdate(3i)”=\>“18”,  
“sponsors”=\>“Ford”, “first\_name”=\>“Jackson”, “last\_name”=\>“Tong”,  
“location”=\>“PJ, Selangor”, “division\_ids”=\>[“2”]}}

My car partial:

form\_for (@driver)  
…  
\<% fields\_for “driver[car\_attributes][]”, car do |car\_form| %\>

 \<%= car\_form.text\_field :number, :class=\>'no' %\> \<%= car\_form.text\_field :make %\> \<%= car\_form.text\_field :model %\> \<% end %\> Photo: \<%= file\_field\_tag "driver[car\_attributes][][photo\_attributes] []", :size=\>17 %\> 

Driver.rb

# Virtual attributes for child model Car

def car\_attributes=(car\_attributes)  
car\_attributes.each do |attributes|  
cars.build(attributes)  
end  
end

Car.rb:

# Virtual attribute for child model Photo (for mass-assignment)

def photo\_attributes=(photo\_attributes)  
photo\_attributes.each do |attributes|  
photos.build(attributes)  
end  
end

DriversController.new

def new  
@title = “New Driver”  
@driver = Driver.new  
@driver.cars.build  
@driver.cars.each do |car|  
car.photos.build  
end

```
respond_to do |format|
  format.html # new.html.erb
  format.xml { render :xml => @driver }
end

```

end

view/drivers/new  
…

  
Cars:   
  
  
Enter car details  
\<%= render :partial =\> ‘car’, :collection =\> @driver.cars  
%\>  
  
\<%= add\_car\_link “Insert a car” %\>  
  
  
…

I will really appreciate your help.
