【发布时间】:2012-10-31 23:03:55
【问题描述】:
我有一个包含虚拟属性: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'))
但这似乎有点笨拙。有没有其他方法可以解决这个问题?
【问题讨论】:
标签: ruby-on-rails-3 forms associations nested-attributes virtual-attribute