问题
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 !@states.contains?(add.state)
@states.push add
That just seems like bad form.
回答1:
@states = People.where(first_name: 'Bob').uniq.pluck(:state)
来源:https://stackoverflow.com/questions/10130818/get-distinct-elements-from-a-rails-activerecord-query