How to call a method on an object in a nested form in Ruby on Rails 3?

旧巷老猫 提交于 2019-12-02 06:52:26

问题


I have these two models

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?

In my Items model I have this method:

def total
  price * quantity
end

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>

What am I missing here?


回答1:


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 %>

with

<%= f.object.total %>


来源:https://stackoverflow.com/questions/9505453/how-to-call-a-method-on-an-object-in-a-nested-form-in-ruby-on-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!