Skip to content


Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP


DISTINCT gets added to generated SQL twice when using #uniq and joining another table #266

twinge opened this Issue · 4 comments

4 participants

Josh Starcher Marc Schütz Peter Walker Mislav Marohnić
Josh Starcher

I'm using postgres (haven't tried this in mysql)

@contacts = @contacts.includes(:addresses).where('' => params[:city])
@contacts = @contacts.uniq
@contacts =[:page])

<%= will_paginate @contacts %>

Generates the following invalid sql:

SELECT  DISTINCT DISTINCT "contacts".id, AS alias_0, AS alias_1 FROM "contacts" LEFT OUTER JOIN "contact_people" ON "contact_people"."contact_id" = "contacts"."id" LEFT OUTER JOIN "people" ON "people"."id" = "contact_people"."person_id" LEFT OUTER JOIN "taggings" ON "taggings"."taggable_id" = "contacts"."id" AND taggings.context = 'tags' AND "taggings"."taggable_type" = 'Contact' LEFT OUTER JOIN "tags" ON "tags"."id" = "taggings"."tag_id" LEFT OUTER JOIN "addresses" ON "addresses"."addressable_id" = "contacts"."id" AND "addresses"."addressable_type" = 'Contact' WHERE "contacts"."account_list_id" = 471 AND "addresses"."state" IN ('AGS', 'ALB') ORDER BY LIMIT 30 OFFSET 0
Marc Schütz

This is actually a bug in ActiveRecord (see Empact/rails@2121059).
For now, you can workaround this by placing a file with the following contents in your config/initializers directory:

module ActiveRecord
  module FinderMethods
    def construct_limited_ids_condition(relation)
      orders = { |val| val.presence }.compact
      values = @klass.connection.distinct("#{@klass.connection.quote_table_name table_name}.#{primary_key}", orders)

      relation = relation.dup
      relation.uniq_value = false # avoids SELECT DISTINCT DISTINCT

      ids_array = {|row| row[primary_key]}
      ids_array.empty? ? raise(ThrowResult) : table[primary_key].in(ids_array)
Peter Walker

The link to the bug is no longer working. Any updates? This issue is still affecting me.

Marc Schütz

The commit has been retracted by its author in favour of a different solution, which isn't merged yet:

Mislav Marohnić

Yup, Active Record bug. Glad to know it's being worked on! Closing this issue

Mislav Marohnić mislav closed this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.