我正在使用Ryan Bates nested_form gem(https://github.com/ryanb/nested_form)并在格式化“编辑”表单上的值时遇到问题。
我目前正在我的一些“非嵌套”表单字段中使用它,效果很好!但是当我在其中一个嵌套元素上以相同的方式格式化时,我得到一个'未定义的方法错误'
代码处理“非嵌套字段”
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'
答案 0 :(得分:1)
使用
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
将返回您在Location
中引用的nested_form_for
的实例,而retail_weekly_price
表中不存在locations
字段,您会收到错误
undefined method 'retail_weekly_price' for #<Location
product_form.object
会返回Product
中引用的fields_for
个实例。通过它访问retail_weekly_price
字段不会有任何问题。
此外,ActionView
辅助方法名称为number_to_currency
而非number_with_currency