2016-11-10 78 views
1

我有一個項目表,我試圖在Ruby中使用.sum方法獲得總購買量。我不知道爲什麼它不起作用。試圖在Ruby中獲得總和 - NameError

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 

物品控制器:

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> 

錯誤:

enter image description here

+1

首先做'項目= Item.all'在'purchase_total'方法調用之前'items.sum ...' – meshpi

+2

還(出了問題的範圍),你可以將這些計算(天,周,月)到項目範圍內,如:'scope:daily - > {where('created_at> =? AND created_at <=?',Time.zone.now.beginning_of_day,Time.zone.now.end_of_day)}'並在控制器中請求它們:'@daily_count = Item.daily.count' –

回答

1

您需要在模型類方法:

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

還是在SQL做計算(這是更高性能):

def self.purchase_total 
    sum(:bought_for) 
end 

並在視圖中調用此關係中的方法:

<td><%= number_to_currency(@items.purchase_total) %></td> 
0
**One simple way but not optimized:** 

def purchase_total 
    items.sum(&:bought_for) 
end 

replace with 

def purchase_total(items) 
    items.sum(&:bought_for) 
end 

And Update call 

item.purchase_total(@items) 


**Another way:** 

In Controller 

@items = Item.all 
@purchase_total = @items.sum(&:bought_for) 

And in erb 
<td><%= number_to_currency(item.purchase_total) %></td> 

replace with 

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