我有一個交易模型
create_table "transactions", force: :cascade do |t|
t.bigint "hire_id"
t.bigint "withdraw_id"
t.bigint "user_by_id"
t.bigint "user_to_id"
t.string "reference"
t.integer "status"
t.integer "price"
t.integer "transaction_type"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["hire_id"], name: "index_transactions_on_hire_id"
t.index ["user_by_id"], name: "index_transactions_on_user_by_id"
t.index ["user_to_id"], name: "index_transactions_on_user_to_id"
t.index ["withdraw_id"], name: "index_transactions_on_withdraw_id"
end
Transaction_type 是一個列舉,所以我的事務控制器上有這個
@debit = Transaction.where(transaction_type: "Debit").sum(:price)
@credit = Transaction.where(transaction_type: "Credit").sum(:price)
我想生成 current_user (current_user.id==user_by_id) 的總貸方和借方
請問我該怎么做?
我試過做
@total_credit_by_user = @credit.group_by(&:user_by_id).sum(:price)
@total_debit_by_user = @debit.group_by(&:user_by_id).sum(:price)
在我看來,我有
<%= @total_credit_by_user[current_user.id] %>
<%= @total_debit_by_user[current_user.id] %>
但我得到undefined method ' for :price:Symbol`
當 current_user.id==user_by_id 時,如何計算 current_user 的總貸方和借方
uj5u.com熱心網友回復:
盡管它們看起來很相似,但Hash 的sum方法與 ActiveRecord 關系的sum方法不同。呼叫group_by關系會回傳一個 Hash 物件,該物件的sum方法不接受列名作為引數。您可以改用group,這將執行GROUP BY并允許您sum在 ActiveRecord 關系上使用。
在這種情況下,如果您需要每個用戶的總信用額地圖,您可以更新控制器邏輯以group與 結合使用sum,如下所示:
credits = Transaction.where(transaction_type: "Credit")
@total_credit_by_user = credits.group(:user_by_id).sum(:price)
然后,您可以通過傳入他們的 ID 來訪問所需用戶的總積分:
@total_credit_by_user[current_user.id]
如果您只想獲取當前用戶的總信用額度,您可以將上述查詢修改為以下內容:
@total_credit = credits.where(user_by_id: current_user.id).sum(:price)
然后就可以@total_credit直接使用視圖中的值了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/464550.html
標籤:轨道上的红宝石 红宝石 ruby-on-rails-6
上一篇:RailsArel如何按選擇分組
