我正在使用Ryan Bates nested_form gem (https://github.com/ryanb/nested_form)并遇到一个问题,当涉及到在我的'edit'表单上格式化值时。
我目前在我的一些"未嵌套"表单字段上使用这个,它工作得很好!但是,当我以相同的方式对其中一个嵌套元素进行格式化时,我得到一个'未定义方法错误''
' unnested Fields'的代码
value: number_with_delimiter(f.object.reserve_price, precision: 2)
编辑时嵌套的表单字段
<div id="products">
<%= f.fields_for :products, :wrapper => false do |product_form| %>
<div class="form-group">
<div class="input-group col-md-4">
<div class="input-group-addon">$</div>
<%= product_form.text_field :retail_weekly_price, class: "form-control", placeholder: 'Retail Weekly Rate Card', required: true, (***add value call results in error***) %>
<div class="input-group-addon">.00</div>
</div>
</div>
</div>
<% end %>
</div>
新增错误日志
ActionView::Template::Error (undefined method `retail_weekly_price' for #<Location:0x007fd46baa35b0>):
160: <div class="form-group">
161: <div class="input-group col-md-4">
162: <div class="input-group-addon">$</div>
163: <%= product_form.text_field :retail_weekly_price, class: "form-control", placeholder: 'Retail Weekly Rate Card', required: true, value: number_with_currency(f.object.retail_weekly_price, precision: 2) %>
164: <div class="input-group-addon">.00</div>
165: </div>
166: </div>
app/views/locations/_edit_form.html.erb:163:in `block (2 levels) in _app_views_locations__edit_form_html_erb__1967616523010840695_70275187628360'
app/views/locations/_edit_form.html.erb:137:in `block in _app_views_locations__edit_form_html_erb__1967616523010840695_70275187628360'
app/views/locations/_edit_form.html.erb:1:in `_app_views_locations__edit_form_html_erb__1967616523010840695_70275187628360'
app/views/locations/edit.html.erb:1:in `_app_views_locations_edit_html_erb__1956197158500275006_70275237765300'
使用
value: number_to_currency(product_form.object.retail_weekly_price, precision: 2)
不是value: number_with_currency(f.object.retail_weekly_price, precision: 2)
由于retail_weekly_price
字段在products
表中。
f.object
将返回您在nested_form_for
中引用的Location
实例,并且由于retail_weekly_price
字段不存在于locations
表中,您收到错误
undefined method 'retail_weekly_price' for #<Location
product_form.object
将返回fields_for
引用的Product
的实例。通过它访问retail_weekly_price
字段不会有任何问题。
另外,ActionView
辅助方法名称是number_to_currency
而不是number_with_currency