0
votes

I have a table named property_audit_version_histories. i am fetching the records using the following code

@version_logs = PropertyAuditVersionHistory
                    .includes(:property_audit_version, :user)
                    .where(property_audit_version_id: params[:id])

The result contain 3 records, 2 of which have the same action and user_id Now i need to group the records using the columns action, user_id

I am getting the following error when i try to group the records

@version_logs = PropertyAuditVersionHistory
                        .includes(:property_audit_version, :user)
                        .where(property_audit_version_id: params[:id])
                        .group("action, user_id")

PG::GroupingError: ERROR:  column "property_audit_version_histories.id" must appear in the GROUP BY clause or be used in an aggregate function

Based on the thread PG::GroupingError: ERROR: column "events.id" must appear in the GROUP BY clause or be used in an aggregate function i have modified the code as follows

@version_logs = PropertyAuditVersionHistory
                    .includes(:property_audit_version, :user)
                    .group("property_audit_version_histories.id")
                    .where(property_audit_version_id: params[:id])
                    .group("action, user_id")

Now the error is gone but still the result is having 3 records. After grouping i expect only 2 records. enter image description here

Any idea on how to fix this?

2
could you add the resulting query from logs?GorillaApe
SELECT "property_audit_version_histories".* FROM "property_audit_version_histories" WHERE "property_audit_version_histories"."property_audit_version_id" = $1 GROUP BY property_audit_version_histories.id, action, user_id [["property_audit_version_id", 44]]prajeesh

2 Answers

0
votes

You cant select all columns like mysql in postgresql when doing aggregrates.

So I guess this should work.

@version_logs = PropertyAuditVersionHistory    
                    .where(property_audit_version_id: params[:id])
                    .group("action", "user_id", "property_audit_version_id")
                    .select("user_id", "action", "property_audit_version_id")

I dont know how is your model but this should work. If you need more fields let me know

0
votes

What you need to do is specify which columns you want with

  .select("user_id")

But for the columns you know will be the same use max(columnName) as columnName

for example:

.select("MAX(user_id) as user_id, action")

Make sure you are 100% sure that those columns will be the same value after grouping.