Home > Blockchain >  PG::UndefinedFunction: ERROR: function count(bigint, integer) does not exist in rails console
PG::UndefinedFunction: ERROR: function count(bigint, integer) does not exist in rails console

Time:11-08

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!

CodePudding user response:

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)

CodePudding user response:

If I understand correctly, you want to count all orders grouped by status? If so:

Order.pluck(:id, :status).group_by { |o| o[1] }.count
  • Related