Skip to content

Instantly share code, notes, and snippets.

@jc00ke
Created November 9, 2013 19:56
Show Gist options
  • Save jc00ke/7389216 to your computer and use it in GitHub Desktop.
Save jc00ke/7389216 to your computer and use it in GitHub Desktop.
Wanted distinct column values via a has_many relation. Needed #select and #pluck.
class Student < ActiveRecord::Base
belongs_to :teacher
# neighborhood: string
end
class Teacher < ActiveRecord::Base
has_many :students
def neighborhoods
self.students.select(:neighborhood).uniq.pluck(:neighborhood)
end
end
@jc00ke
Copy link
Author

jc00ke commented Nov 9, 2013

Adding the select(:neighborhood) allowed the uniq to generate the DISTINCT in the SQL query.

Reordering it to:

self.students.pluck(:neighborhood).uniq

would have been OK, but the uniq would have been performed in Ruby on an array. Probably OK, but might as well use the db to do this.

@jc00ke
Copy link
Author

jc00ke commented Nov 9, 2013

Oh, and if the args to select and pluck are the same string, then the query will collapse the fields.

t = Teacher.first
t.students.select(:neighborhood).uniq.pluck(:neighborhood)

yields

SELECT DISTINCT neighborhood, "students"."neighborhood" FROM "students"...

and

t = Teacher.first
t.students.select('neighborhood').uniq.pluck('neighborhood')

yields

SELECT DISTINCT neighborhood FROM "students"...

both return the same result, but the latter is the query we'd actually want.

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