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>
錯誤:
首先做'項目= Item.all'在'purchase_total'方法調用之前'items.sum ...' – meshpi
還(出了問題的範圍),你可以將這些計算(天,周,月)到項目範圍內,如:'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' –