Trying to get the sum in Ruby - NameError -


i have items table , trying total amount of purchases using .sum method in ruby. 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 |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 >= ? , created_at <= ?', time.zone.now.beginning_of_day, time.zone.now.end_of_day)   @items_week = item.all.where('created_at >= ? , created_at <= ?', time.zone.now.beginning_of_week, time.zone.now.end_of_week)   @items_month = item.all.where('created_at >= ? , 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

you need class method in model:

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

or calculation in sql (which performant):

def self.purchase_total   sum(:bought_for) end 

and call method on relation in view:

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

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -