TAGS :Viewed: 8 - Published at: a few seconds ago

[ Only list unique values ]

I have two collection_select drop down menus that are currently set up like so:

<div class="field">
    <%= f.label :country_cont, "Country" %>
    <%= f.collection_select(:country_cont, Country.all, :country, :country) %>
</div>

<div class="field">
    <%= f.label :city_cont, "City" %>
    <%= f.collection_select(:city_cont, Job.all, :city, :city) %>
</div>

What I would like is for the drop down to only display a list of unique values from my database tables (for example in City rather than displaying London 5 times because there are 5 rows that have that city I would like London to only be listed once).

Any advice on this would be much appreciated! :)

Answer 1


I would create a scope in your Job class that filters by unique city. How you actually implement this will depend on your database. The example below uses MySQL syntax:

class Job
  scope :unique_by_city, lambda { select('DISTINCT(city)') }
end

In your view

<div class="field">
    <%= f.label :city_cont, "City" %>
    <%= f.collection_select(:city_cont, Job.unique_by_city, :city, :city) %>
</div>

An alternate version would be if you don't have many Jobs in your database, just load all the records and do it in ruby:

class Job
  def self.unique_by_city
    all.uniq_by(&:city)
  end
end

Answer 2


a better scope to the below answer also see

class Job
  scope :unique_by_city, lambda { select(:city).uniq}
end