Get distinct elements from a Rails ActiveRecord query

女生的网名这么多〃 提交于 2019-12-11 16:49:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!