Mike Wiesenhart Mike Wiesenhart - 27 days ago 12
Ruby Question

Trying to get the sum in Ruby - NameError

I have an items table and I am trying to get the total amount of purchases using the

.sum
method in Ruby. I am not sure why it's not working.

Model.rb

class Item < ActiveRecord::Base
def profit_calc
sold_for - bought_for - fees - shipping
end

def purchase_total
items.sum(&:bought_for)
end

scope :visible, -> { where(sold: false) }
scope :sold, -> { where(sold: true) }
end


Schema.rb

create_table "items", force: :cascade do |t|
t.string "description"
t.float "bought_for"
t.float "sold_for"
t.float "fees"
t.float "shipping"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "sold", default: false
end


Items Controller:

def statistics
@items = Item.all
@items_day = Item.all.where('created_at >= ? AND created_at <= ?', Time.zone.now.beginning_of_day, Time.zone.now.end_of_day)
@items_week = Item.all.where('created_at >= ? AND created_at <= ?', Time.zone.now.beginning_of_week, Time.zone.now.end_of_week)
@items_month = Item.all.where('created_at >= ? AND created_at <= ?', Time.zone.now.beginning_of_month, Time.zone.now.end_of_month)
end


Statistics.html.erb:

<h1 id="title">Statistics</h1>
<br>

<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Total</th>
<th>Today</th>
<th>Week</th>
<th>Month</th>
<th>Total Purchases</th>
<th>Total Fees</th>
<th>Total Shipping</th>
<th>Total Sales</th>
<th>Total Profit</th>
</tr>
</thead>

<tbody>
<tr>
<td><%= number_with_delimiter(@items.count) %></td>
<td><%= @items_day.count %></td>
<td><%= @items_week.count %></td>
<td><%= @items_month.count %></td>
<td><%= number_to_currency(item.purchase_total) %></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>


Error:

enter image description here

Answer

You need class method in the model:

def self.purchase_total
  to_a.sum(&:bought_for)
end

Or do calculation in the SQL:

def self.purchase_total
  sum(:bought_for)
end

And call this method on relation in the view:

<td><%= number_to_currency(@items.purchase_total) %></td>