Tyler DeWitt
Tyler DeWitt

Reputation: 23576

Get distinct elements from a Rails ActiveRecord query

I've got a query in Rails like this:

@addresses=People.select("first_name, state").where("first_name = 'Bob'")

Is there a way I can iterate over addresses and pull out the distinct states, so that I know in which states someone named bob lives?

I'm trying to avoid:

@states = []
@address.each.do |add|
  if [email protected]?(add.state)
    @states.push add

That just seems like bad form.

Upvotes: 0

Views: 4223

Answers (1)

jdoe
jdoe

Reputation: 15771

@states = People.where(first_name: 'Bob').uniq.pluck(:state)

Upvotes: 5

Related Questions