【问题标题】:How to count the sum of Invoices by last year using SQL in Rails?如何在 Rails 中使用 SQL 计算去年的 Invoices 总和?
【发布时间】: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


【解决方案1】:

我会试试的

Invoice
  .where(created_at: (Time.current.beginning_of_year..Time.current.end_of_year))
  .sum(:amount)

或者你可以在你的模型中定义一个范围,比如

scope :by_year, -> (year) { where('extract(year from created_at) = ?', year) }

并像这样使用它

Invoice.by_year(Date.today.year).sum(:amount)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    • 2011-05-18
    • 2018-11-30
    • 2010-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多