Skip to content

Commit

Permalink
Fix Template.latest_version ambiguity error
Browse files Browse the repository at this point in the history
- Prior to this commit, the following error was encountered when applying the search filter within `/org_admin/templates`:

```
ActiveRecord::StatementInvalid - PG::AmbiguousColumn: ERROR:  column reference "id" is ambiguous
LINE 1: SELECT COUNT(DISTINCT id) FROM (SELECT MAX(version) AS versi...
                              ^:
  app/views/layouts/_paginable.html.erb:5
  app/controllers/concerns/paginable.rb:82:in `paginable_renderise'
  app/controllers/paginable/templates_controller.rb:25:in `index'
```

- Tracing the code reveals that the query encountering this error is `Template.includes(:org).latest_version.where(customization_of: nil).distinct.total_count`.

- Although `SELECT "templates.*"` is the default behaviour of the `.latest_version` scope, the ambiguity error is raised unless `.select('templates.*')` is added explicitly.
  • Loading branch information
aaronskiba committed Jan 13, 2025
1 parent 2d707d5 commit 1262869
Showing 1 changed file with 4 additions and 0 deletions.
4 changes: 4 additions & 0 deletions app/models/template.rb
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,10 @@ class Template < ApplicationRecord
AND current.family_id = templates.family_id
INNER JOIN orgs ON orgs.id = templates.org_id
SQL
# `SELECT "templates.*"` is this scope's default behavior, but it must be explicitly
# specified to prevent `PG::AmbiguousColumn` errors when `.distinct.total_count` is used
# (e.g. in `app/views/layouts/_paginable.html.erb`)
.select('templates.*')
}

# Retrieves the latest customized versions, i.e. those with maximum version
Expand Down

0 comments on commit 1262869

Please sign in to comment.