Created
November 9, 2013 19:56
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Student < ActiveRecord::Base | |
belongs_to :teacher | |
# neighborhood: string | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Teacher < ActiveRecord::Base | |
has_many :students | |
def neighborhoods | |
self.students.select(:neighborhood).uniq.pluck(:neighborhood) | |
end | |
end |
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
Adding the
select(:neighborhood)
allowed theuniq
to generate theDISTINCT
in the SQL query.Reordering it to:
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.