我有这两个模型
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
以及这个发布到两个模型的嵌套(!)表单:
<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 %>
如何对表单中的项目进行计算?
在我的 Items
模型中,我有这个方法:
def total
price * quantity
end
但是,在表单中我无法让它与 f.total
一起使用。我不断收到此错误:
undefined method `total' for #<ActionView::Helpers::FormBuilder:0x10ec05558>
我在这里缺少什么?
最佳答案
您不是在模型对象上调用方法,而是在 f
上调用方法,它是一个表单助手 (ActionView::Helpers::FormBuilder
)。错误消息对此给出了提示。
要调用该项目,您需要更换
<%= f.total %>
与
<%= f.object.total %>
关于ruby-on-rails - 如何在 Ruby on Rails 3 中以嵌套形式调用对象的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9505453/