开发者

Rails 3 Nested Model Form: Can not mass assign protected attribute

I currently have a form set up with nested models - all going according to plan so far. The form allows me to create a sale, and from that I can create a customer and a vehicle (separate models).

The problem comes when I try to create a registration number, which is a separate model nested from vehicle; essentially I can get a text box to appear on the form, but trying to create a registration number results in a can not mass assign protected attribute :registration_number error in the console, and when editing a sale that includes a vehicle with a registration number, the text box is empty.

The models involved are:

class Sale < ActiveRecord::Base
  attr_accessible :customer_id, :vehicle_id, :sale_date, 
                  :customer_attributes, :vehicle_attributes

  belongs_to :customer
  accepts_nested_attributes_for :customer

开发者_开发百科  belongs_to :vehicle
  accepts_nested_attributes_for :vehicle

end

and

class Vehicle < ActiveRecord::Base
  attr_accessible :first_registration_date, :hidden, :registration_numbers_attributes

  has_many :sales
  has_many :customers, :through => :sales

  has_many :vehicle_registration_numbers, :dependent => :delete_all
  has_many :registration_numbers, :through => :vehicle_registration_numbers
  accepts_nested_attributes_for :registration_numbers, :allow_destroy => true

end

and

class RegistrationNumber < ActiveRecord::Base

  attr_accessible :number

  has_many :vehicle_registration_numbers, :dependent => :delete_all
  has_many :vehicles, :through => :vehicle_registration_numbers

end

and

class VehicleRegistrationNumber < ActiveRecord::Base

  belongs_to :vehicle
  belongs_to :registration_number

end

The form in question is:

<%= form_for @sale, :html => {:class => 'fullform'} do |f| %>

<%= field_set_tag 'Customer Details' do %>
    <%= f.fields_for :customer do |builder| %>
        <snip>
    <% end %>
<% end %>

<%= field_set_tag 'Vehicle Details' do %>
    <%= f.fields_for :vehicle do |vehicle_builder| %>
        <snip>
            <%= f.fields_for :registration_numbers do |registration_number_builder| %>
                <%= registration_number_builder.text_field :number, :class => 'formtxtbox-short' %>
            <% end %>
    <% end %>
<% end %>

<% end %>

Any assistance would be greatly appreciated - thanks!


You mis-nested your resources, see arrow below.

<%= field_set_tag 'Vehicle Details' do %>
  <%= f.fields_for :vehicle do |vehicle_builder| %>
    <snip>
 ===>> <%= vehicle_builder.fields_for :registration_numbers do |registration_number_builder| %>
            <%= registration_number_builder.text_field :number, :class => 'formtxtbox-short' %>
        <% end %>
  <% end %>
<% end %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜