Austin
Austin

Reputation: 37

Rails model method returning wrong value

In the Rails console I am attempting to call a method in my model that returns the sum of the quantity of a user's orders.

The method is:

def self.user_total(current_user)
  quantity = UserOrder.select("sum(quantity)").where(user_id: current_user)
  quantity
end

If I run Order.user_total(1) in rails console it returns: #<ActiveRecord::Relation [#<UserOrder id: nil>]>

However, the SQL generated is correct:

SELECT  sum(quantity) FROM "user_orders" 
WHERE "user_orders"."user_id" = $1 LIMIT $2 
[["user_id", 1], ["LIMIT", 11]]

And if I run the SQL in dbconsole, it returns the correct sum:

SELECT  sum(quantity) FROM user_orders 
WHERE user_orders.user_id = 1;

=> 115

It will also return #<ActiveRecord::Relation [#<UserOrder id: nil>]> if I remove the where constraint.

In rails console if I just generate simple SQL query to find all of the quantities, it returns

irb(main):005:0> UserOrder.select("quantity")
  UserOrder Load (0.4ms)  SELECT  "user_orders"."quantity" FROM "user_orders" LIMIT $1  [["LIMIT", 11]]
=> #<ActiveRecord::Relation [
#<UserOrder id: nil, quantity: 1>
, #<UserOrder id: nil, quantity: 1>
, #<UserOrder id: nil, quantity: 1>
, #<UserOrder id: nil, quantity: 1>
, #<UserOrder id: nil, quantity: 1>
, #<UserOrder id: nil, quantity: 8>
, #<UserOrder id: nil, quantity: 102>
]>

So I can kind of see where UserOrder id: nil is coming from, but at the same time why would it return that "column" (for lack of a better word) instead of just the quantities or sum of quantity in the other examples?

Upvotes: 1

Views: 373

Answers (1)

Chris Peters
Chris Peters

Reputation: 18090

There is a method for querying the sum:

UserOrder.where(user_id: current_user).sum(:quantity)

As a style point, I'd say that naming the argument current_user doesn't make sense in the model layer because it shouldn't care who the user is that's being queried, be it the "current" logged in user or some other user.

Upvotes: 3

Related Questions