我有一个包含虚拟属性的嵌套表单: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'))
但这似乎有点笨拙。还有其他方法可以解决这个问题吗?