AaronDT AaronDT - 1 year ago 84
Ruby Question

How do I return distinct values with options_from_collection_for_select helper?

I am trying to return the countries of my products within a select tag using


I have a Product model, with country as a column name. My code looks like this

<%= select_tag(:country, options_from_collection_for_select(Product.all.order(:country), :id, :country), :prompt => "Alle Länder") %>

However it gives me each country more than once in the dropdown field i.e. each country appears 20 times.

Now I've been trying to use a solution suggested in a similar question, like so

options_from_collection_for_select(Product.all.pluck('DISTINCT country'), :id, :country), :prompt => "Alle Länder") %>

however I get an error stating:

"undefined method `country' for "Spain":String
Did you mean? count"

Now I cant figure out which method is appropriate in this case.

Thank you very much!

Answer Source

You get non-uniq values because there's more, than one row in db with given country.

= f.select :country,
  { include_blank: 'Select country' }

If you want to still use select_tag:

= select_tag :country,
  { include_blank: 'Select country' }