如何在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屋!
查看全文