Tintin81
Tintin81

Reputation: 10207

How to perform calculations on nested form items?

I am fairly new to Rails and 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 self.total
    price * quantity
  end
  ...
end

... and a nested (!) form that creates new invoice records and their associated items.

However, I find it very difficult to perform calculations on these items. For example next to each item I would like to put the total for this item using the total method above.

Unfortunately, it's not working. In my form I put this next to each item:

<%= @invoice.items.amount %>

which is derived from my controller:

def new      
  @invoice = Invoice.new
  3.times {@invoice.items.build}
end

It keeps throwing an error saying undefined local variable or method price

What am I missing here??

Thanks for any help.

Upvotes: 0

Views: 338

Answers (1)

TheDelChop
TheDelChop

Reputation: 7998

You have created a class method on Item, when I think what you want is an instance method.

class Item < ActiveRecord::Base
  belongs_to :invoice

  def total
    price * quantity
  end
  ...
end

which you can call on an individual item @item.total or, if you do you the total of all the items, then you'd need to do something like this:

class Item < ActiveRecord::Base
  belongs_to :invoice

  def self.total
    all.collect { |item| item.price * item.quantity }
  end
  ...
end

@invoice.items.total

Hope that helps.

Upvotes: 1

Related Questions