如何在 Ruby on Rails 3 中以嵌套形式调用对象的方法? [英] How to call a method on an object in a nested form in Ruby on Rails 3?
本文介绍了如何在 Ruby on Rails 3 中以嵌套形式调用对象的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这两个模型
class Invoice < ActiveRecord::Base
has_many :items
accepts_nested_attributes_for :items
...
end
class Item < ActiveRecord::Base
belongs_to :invoice
def total
price * quantity
end
...
end
这个嵌套的 (!) 表单同时发布到两个模型:
and this nested (!) form that posts to both models:
<h1>Add an Invoice</h1>
<%= form_for @invoice do |f| %>
<p>
<%= f.label :recipient %>
<%= f.text_field :recipient %> </p>
<p>
<%= f.label :date %>
<%= f.text_area :date %>
</p>
<h2>Items</h2>
<p>
<%= f.fields_for(:items) do |f| %>
<%= f.label :description %>
<%= f.text_field :description %>
<%= f.label :price %>
<%= f.text_field :price %>
<%= f.label :quantity %>
<%= f.text_field :quantity %>
<%= f.label :total %>
<%= f.total %><!-- this method call is not working! -->
<% end %>
</p>
<%= f.submit %>
<% end %>
如何对表单中的项目进行计算?
How can I do calculations on my items within the form?
在我的 Items
模型中,我有这个方法:
In my Items
model I have this method:
def total
price * quantity
end
但是,在表单中我无法让它与 f.total
一起使用.我不断收到此错误:
However, in the form I can't get it to work with f.total
. I keep getting this error:
undefined method `total' for #<ActionView::Helpers::FormBuilder:0x10ec05558>
我在这里遗漏了什么?
推荐答案
您不是在模型对象上调用方法,而是在 f
上调用方法,这是一个表单助手 (ActionView::Helpers::FormBuilder
).错误消息对此给出了提示.
You are calling a method not on your model object, but on f
, which is a form helper (ActionView::Helpers::FormBuilder
). Error message gives a hint to this.
要调用该项目,您需要替换
To call on the item, you need to replace
<%= f.total %>
与
<%= f.object.total %>
这篇关于如何在 Ruby on Rails 3 中以嵌套形式调用对象的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文