Home > Software design >  Sum all transaction by current_user
Sum all transaction by current_user

Time:04-27

I have a transaction model

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 is an enum, so I have this on my transaction controller

@debit = Transaction.where(transaction_type: "Debit").sum(:price)
@credit = Transaction.where(transaction_type: "Credit").sum(:price)

I want to generate the total credit and debit of current_user (current_user.id==user_by_id)

How can I do it, please?

I have tried to do

@total_credit_by_user = @credit.group_by(&:user_by_id).sum(:price)
@total_debit_by_user = @debit.group_by(&:user_by_id).sum(:price)

and in my view, I have

<%= @total_credit_by_user[current_user.id] %>
<%= @total_debit_by_user[current_user.id] %>

But I am getting undefined method ' for :price:Symbol`

How can I sum the total credit and debit by a current_user when current_user.id==user_by_id

CodePudding user response:

Although they appear similar, the sum method for a Hash is different than the sum method for an ActiveRecord relation. Calling group_by on a relation returns a Hash object, whose sum method does not accept a column name as an argument. You can use group instead, which will perform a GROUP BY and allow you to use sum on the ActiveRecord relation.

In this case, if you need a map of the total credit amounts per user, you can update the controller logic to use group in conjunction with sum, like so:

credits = Transaction.where(transaction_type: "Credit")
@total_credit_by_user = credits.group(:user_by_id).sum(:price)

You can then access the total credits for the desired user by passing in their ID:

@total_credit_by_user[current_user.id]

If you only want to fetch the total credit amount for the current user you can modify the above query to the following:

@total_credit = credits.where(user_by_id: current_user.id).sum(:price)

Then you can use the @total_credit value in the view directly.

  • Related