我有一个模型,它有一些非模型属性的送货地址。非模型数组元素的Rails attr_accessor
其中一个元件是:
<%= form_for Checkout.new, url: placeorder_url do |f| %>
<%= f.text_field "shipping[firstname]", value: nil, class: 'form-control', placeholder: 'First Name' %>
<% end %>
输出是
<input value="" class="form-control" placeholder="First Name" type="text" name="checkout[shipping[firstname]]" id="checkout_shipping[firstname]">
但是当在模型相同的添加验证,我需要首先将其添加到attr_accessor,这我无法做到。模型名称是Checkout,这就是为什么输出html中的结帐。
的模型是:
class Checkout
include ActiveModel::Model
attr_accessor :shipping
validates "shipping[firstname]", presence: true
end
张贴的数据是这样的:
{"checkout"=>
{"shipping"=>
{
"firstname"=>"", "lastname"=>"", "companyname"=>"", "address1"=>"", "address2"=>"", "city"=>"", "state"=>"", "postalcode"=>"", "primaryphone"=>"", "secondaryphone"=>""
}
}
}
没有任何人有任何想法如何允许attr_accessor或任何其他方式来验证相同的自定义数组字段。
我得到的错误是:
undefined method `shipping[firstname]' for #<Checkout:0x00000001789de8>
名称不正确'结帐[运费[名字]'应该是'结帐[运费] [名字]' –
,你将需要创建与第一ATTR访问名称,然后用'params [checkout] [shipping] [firstname]'分配它[ –
@DeepakMahakale Hi Deepak,但是要写同样的东西,f.text_field“shipping [firstname]”,value:nil,class:'form 'control',占位符:'名字' –