0

我有一个包含虚拟属性的嵌套表单:card_number 和:card_verification。当我尝试在控制器更新操作中使用这些构建时,我得到 ActiveRecord::UnknownAttributeError。

模型有一个简单的 has_one 关系,其中约会 has_one 订单

#/models/appointment.rb
class Appointment < ActiveRecord::Base
  has_one :order
  accepts_nested_attributes_for :order

  attr_accessible (...)
end

#/models/order.rb
class Order < ActiveRecord::Base
  belongs_to :appointment

  attr_accessible :email, (...)
  attr_accessor :card_number, :card_verification
end

我正在生成这样的表格:

# /views/appointments/edit.html.erb
<%= form_for @appointment do |f| %>
  ...
  <%= f.fields_for @appointment.order do |builder| %>
    <%= builder.label :email %>
    <%= builder.text_field :email %> # works fine on its own
    ...
    <%= f.label :card_number %>
    <%= f.text_field :card_number %>

    <%= f.label :card_verification %>
    <%= f.text_field :card_verification %>
  <% end %>
  ...
<% end %>

并在控制器中构建:

# /controllers/appointments_controller.rb
def update
  @appointment = Appointment.find(params[:id])
  @order = @appointment.build_order(params[:appointment]['order']) # This line is failing

  if @appointment.update_attributes(params[:appointment].except('order'))
    # ... Success
  else
    # ... Failure
  end
end

有了这个,Can't mass-assign protected attributes: card_number, card_verification当我尝试使用参数提交更新时出现错误:

{"utf8"=>"✓",
 "_method"=>"put",
 "authenticity_token"=>"KowchWLNmD9YtPhWhYfrNAOsDfhb7XHW5u4kdZ4MJ4=",
 "appointment"=>{"business_name"=>"Name",
 "contact_method"=>"Phone",
 "contact_id"=>"555-123-4567",
 "order"=>{"email"=>"user@example.com",
 "first_name"=>"John",
 "last_name"=>"Doe",
 "card_number"=>"4111111111111111", # normally [FILTERED]
 "card_verification"=>"123", # normally [FILTERED]
 "card_type"=>"visa",
 "card_expires_on(1i)"=>"2015",
 "card_expires_on(2i)"=>"11",
 "card_expires_on(3i)"=>"1",
 "address_line_1"=>"123 Main St",
 "address_line_2"=>"",
 "city"=>"Anywhere",
 "state"=>"CA",
 "country"=>"USA",
 "postal_code"=>"90210"}},
 "commit"=>"Submit",
 "id"=>"2"}

没有包含在表单中的 :card_number 和 :card_verification 值,一切正常。

有谁知道这里出了什么问题?

编辑:

我可以得到这个工作:

@order = @appointment.build_order(params[:appointment]['order'].except('card_number', 'card_verification'))

但这似乎有点笨拙。还有其他方法可以解决这个问题吗?

4

1 回答 1

1

错误消息“无法批量分配受保护的属性”是关于批量分配安全性的。您可以通过 without_protection 忽略批量分配检查。

@order = @appointment.build_order(params[:appointment]['order'], without_protection: true)

此链接说明什么是批量分配安全性。 Rails 内部结构:批量分配安全性

如果要指定大量可分配的属性,请使用 attr_accessible :one, :another 作为模型属性。如果您需要其他非模型属性,请使用 attr_accessor :card_number ,然后使用 attr_accessible :card_number 来声明和公开它。

我看到您在 Order 模型中定义了 card_number 和 card_verfication,但是您使用 form_builder => f 在 html 中定义这两个字段。尝试改用 fields_for 构建器。

于 2012-11-01T06:31:59.003 回答