试图在Ruby中获得总和 - NameError

时间:2016-11-10 14:28:04

标签: ruby-on-rails ruby postgresql

我有一个项目表,我正在尝试使用Ruby中的.sum方法获取总购买量。我不确定为什么它不起作用。

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

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分: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>