Nested models, mass assignment problem

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.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs