如何在Ruby on Rails 3中以嵌套forms调用对象上的方法?
我有这两个型号
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
这个嵌套(!)forms发布到两个模型:
Add an Invoice
Items
如何对表单中的项目进行计算?
在我的Items
模型中,我有这个方法:
def total price * quantity end
但是,在forms上我无法使用f.total
。 我一直收到这个错误:
undefined method `total' for #
我在这里想念的是什么?
您正在调用一个不在模型对象上的方法,而是调用f
,它是一个表单助手( ActionView::Helpers::FormBuilder
)。 错误消息给出了一个提示。
要调用该项目,您需要替换
<%= f.total %>
同
<%= f.object.total %>