Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue with Result Counting in PostgreSQL #62

Closed
sgonyea opened this issue Jun 10, 2011 · 3 comments
Closed

Issue with Result Counting in PostgreSQL #62

sgonyea opened this issue Jun 10, 2011 · 3 comments

Comments

@sgonyea
Copy link

sgonyea commented Jun 10, 2011

For reference, I am using Rails 3.1.0rc4 with arel 2.1.1, and pg 0.11.0

My tests seemed to have exposed this bug. Take the following model:

class Location < ActiveRecord::Base
  belongs_to  :user

  scope :distinct_by_user,      select('DISTINCT ON(user_id) *')
  scope :from_sorted_locations, from('(SELECT locations.* FROM "locations" ORDER BY locations.id DESC) AS sorted_locations')
  scope :recent_user_locations, distinct_by_user.from_sorted_locations
end

The SQL Query that's generated is below the ruby code:

Location.recent_user_locations
# SELECT DISTINCT ON(user_id) * FROM (SELECT locations.* FROM "locations" ORDER BY locations.id DESC) AS sorted_locations

Location.recent_user_locations.size
# SELECT COUNT(*) FROM (SELECT locations.* FROM "locations" ORDER BY locations.id DESC) AS sorted_locations

Basically, calling "size" / "count" will go against my own "from" query, but disregard my select query. Once the query is executed, #size / #count return the correct record count.

Thank you!

@njakobsen
Copy link

I just ran into this problem while trying to work around the issue of calling count on a relations with group causing the return value to be an ordered hash instead of an integer. Instead of grouping to remove duplicates, I tried using the slower "SELECT DISTINCT" method, but this was overridden by calling .count() on the relation.

@njakobsen
Copy link

It looks like you can pass :distinct to the count option to ensure the count is distinct. It doesn't get applied automagically, but it should let you count distinct on user_id.

@matthewd
Copy link
Member

Per #523, Arel development is moving to rails/rails.

If this issue is still relevant, please consider reopening it over there. (Note that the Rails repository does not accept feature request issues, and requires reproduction steps that rely on Active Record's documented API.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

3 participants