Ilia Kazantsev
Ilia Kazantsev

Reputation: 13

Can't understand how to sum items price in RoR

Hello I want to make simple shopping cart. I am a beginner in programming. So please help. I have items with prices and i want to sum up them (quantity equals to one).

veiw

<h1>Summ:<%= @items.total %></h1>

model

class Item < ActiveRecord::Base

  def total
      summ = 0
      @items.each do |item|
          summ += item.price
      end
  end

end

What is wrong. I have this error NoMethodError in Items#index

Upvotes: 1

Views: 2846

Answers (4)

Steve Wilhelm
Steve Wilhelm

Reputation: 6260

Look at Enumerable method inject method. You should probably compute this value in the controller and pass it to the view

controller

@summ = @items.inject(0) {|sum, item| sum + item.price }

view

<h1>Summ:<%= @summ %></h1>

Upvotes: 0

Aaron Hinni
Aaron Hinni

Reputation: 14716

Rails defines an Enumerable::sum method that you can call. So your view can look like this:

<h1>Summ: <%= @items.sum(&:price) %></h1>

You could also add a total method to your Order (or whatever model you are using that has_many :items). Something along the lines of:

class Order < ActiveRecord::Base
  has_many :items

  def total
    items.sum(&:price)
  end
end

And then your view:

<h1><%= @order.total %></h1>

Upvotes: 9

nuclearsandwich
nuclearsandwich

Reputation: 455

The instance variable @items you are referencing is set in the controller but is not available in the model, which is where you have total defined. If you have a model which holds a collection of items. The other two answers have addressed the other errors in this code.

Upvotes: 1

Karl Knechtel
Karl Knechtel

Reputation: 61509

1) Your view is apparently looking for the name method, but you have defined the total method. (question was edited to fix this.)

2) You have calculated a summ in the total method, but apparently don't return it from the method.

3) You are defining a method of the Item class, i.e. something that you can call upon an individual item; however, you would like to sum the prices of several items together.

Upvotes: 0

Related Questions