2017-09-06 85 views
0

我有一个模型,它有一些非模型属性的送货地址。非模型数组元素的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> 
+0

名称不正确'结帐[运费[名字]'应该是'结帐[运费] [名字]' –

+0

,你将需要创建与第一ATTR访问名称,然后用'params [checkout] [shipping] [firstname]'分配它[ –

+0

@DeepakMahakale Hi Deepak,但是要写同样的东西,f.text_field“shipping [firstname]”,value:nil,class:'form 'control',占位符:'名字' –

回答

0

添加attr_accessor为姓

class Checkout 
    include ActiveModel::Model 

    attr_accessor :firstname 
end 

然后你可以使用它作为一个属性。利用name产生适当的元素名称

<%= f.text_field :firstname, value: nil,name: 'checkout[shipping][firstname]', class: 'form-control', placeholder: 'First Name' %> 
0

您的名字必须是结帐[运费] [名字],并且无法检出[航运[名字],如在评论中提到。 一种方式来解决这将是像这样:

<%= form_for Checkout.new, url: placeorder_url do |f| %> 
    <%= f.text_field "shipping[firstname]", name: "checkout[shipping][firstname]", value: nil, class: 'form-control', placeholder: 'First Name' %> 
<% end %>