Rails 3嵌套模型表单:无法批量分配受保护的属性

时间:2011-07-16 22:43:09

标签: ruby-on-rails ruby-on-rails-3 nested-forms rails-models

我目前有一个使用嵌套模型设置的表单 - 到目前为止都按计划进行。表单允许我创建销售,从中我可以创建客户和车辆(单独的模型)。

当我尝试创建一个注册号时出现问题,这是一个与车辆嵌套的独立模型;基本上我可以在表单上显示一个文本框,但是尝试创建注册号会导致控制台出现can not mass assign protected attribute :registration_number错误,并且当编辑包含带有注册号的车辆的销售时,文本框是空的。

所涉及的模型是:

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

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

class RegistrationNumber < ActiveRecord::Base

  attr_accessible :number

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

end

class VehicleRegistrationNumber < ActiveRecord::Base

  belongs_to :vehicle
  belongs_to :registration_number

end

有问题的表格是:

<%= 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 %>

非常感谢任何帮助 - 谢谢!

1 个答案:

答案 0 :(得分:3)

您错误地嵌套了资源,请参阅下面的箭头。

<%= 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 %>