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| %>
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
…
Enter car details
<%= render :partial => ‘car’, :collection => @driver.cars
%>
<%= add_car_link “Insert a car” %>
…
I will really appreciate your help.