-1

I have two models Product and Order have a relation between them belongs to product and has_many orders.

#app/models/product.rb
class Product < ApplicationRecord
    has_many :orders, dependent: :destroy
end
#app/models/order.rb
class Order < ApplicationRecord
  belongs_to :product

  enum :status, [:accepted, :shipped, :courier_shiped, :booked, :cancelled, :returned]

end

I have fired the below query in the rails console.

Order.select(:id,:status).group(:id,:status).count

getting the below errors in the rails console.

`exec_params': PG::UndefinedFunction: ERROR:  function count(bigint, integer) does not exist (ActiveRecord::StatementInvalid)
LINE 1: SELECT COUNT(id,status) AS "count_id_status", id,status AS "...

HINT:  No function matches the given name and argument types. You might need to add explicit type casts

need to retrieve all orders group by status column and count all the enums values in the rails console with their appropriate ids.

thanks!

Rahul Gupta
  • 53
  • 1
  • 1
  • 12
  • An order can only have 1 status so... `Order.group(:status).count` [Docs](https://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-count). – engineersmnky Nov 07 '22 at 19:56

1 Answers1

2

Try the following query to get the result, this will group data by status and return a count of ids having the same status. in Rails select with count does not work as count tries to execute the query immediately

 Order.select(:id, :status).group(:status).pluck('status, count(id)')

OR

Order.select('count(id), status').group(:status)
  • i have triggered above query Order.select('count(id), status').group(:status) and get result, [#, #, #, #] , could be also print it's id. – Rahul Gupta Nov 07 '22 at 10:07
  • hm, right. I just verified it on my machine and it does return nil for id, Have you tried the first one, is that working for you it's working for me but returning result in array format – Supriya Medankar Nov 07 '22 at 14:45
  • 1
    I just modified the second query a bit to` Order.select('count(id) as id_count, status').group(:status).map(&:id_count)` and it returns me count, even though we are not able to see it, it exists you can access it for each record using an alias name – Supriya Medankar Nov 07 '22 at 14:50