AaronDT AaronDT - 2 months ago 16
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

options_from_collection_for_select()


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

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

= f.select :country,
  Product.pluck(:country).uniq,
  { include_blank: 'Select country' }

If you want to still use select_tag:

= select_tag :country,
  options_for_select(Product.pluck(:country).uniq),
  { include_blank: 'Select country' }
Comments