【发布时间】:2020-12-13 13:07:47
【问题描述】:
我需要计算去年的所有发票金额。我使用辅助方法来做到这一点,但据我所知,有更好的方法使用 SQL 函数 SUM() 对数据库仅使用一个查询。
我的发票表:
create_table "invoices", force: :cascade do |t|
t.string "title"
t.text "description"
t.string "category"
t.decimal "amount"
t.bigint "user_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["user_id"], name: "index_invoices_on_user_id"
end
我目前使用 Ruby 进行多个数据库查询和总和的方法:
# invoice.rb model has invoices_for_year scope
scope :invoices_for_year, -> { where('extract(year from created_at) = ?', Time.now.strftime("%Y").to_i) }
# invoices_controller.rb in index method has @invoices_for_year
invoices = Invoice.all.available_for(current_user)
@invoices_for_year = invoices.invoices_for_year
# and inside helper I calculate the all amount
def count_year_spend
@invoices_for_year.reduce(0) { | sum, invoice | sum + invoice.amount }
end
如何在 Ruby 中使用 SQL 计算一个请求的数量?
【问题讨论】:
-
sum应该可以工作。 -
感谢 Stefan,使用 sum 方法真的很容易
标签: sql ruby-on-rails ruby