Ruby on Rails: Uniqueness of elements in drop down menu

I'm very new to ROR, and I'm having a problem making the elements in my drop down menu be unique. The menu allows the user to select a Company from a database. At the moment, the menu is listing every Company in the database, because the database holds the same company many times, and I only want that one company to show up once.

<%= f.label :company_name %><br />
<%= f.select( :company_name, Company.all.map {|c| [c.company_name]} ) %>

I know this should be quite simple to fix, but I can't seem to find an answer. Hopefully someone can help.

Thanks in advance.

Answers


You could use:

Company.all.map {|c| c.company_name}.uniq!

But be careful with the id's of the companies and how you're going to use them.

Hope it helps!


Rather than calling uniq! on a fetched array, i would rather use a scope to do that... In your model:

named_scope :unique_by_name, :select => 'DISTINCT name', :order => 'name ASC'

Then you can use:

Company.unique_by_name.map { |company| company.name }

Doing so has the advantage to select the unique companies as unique directly from your database backend, rather than expensively retrieving them all and filtering them afterwards with the uniq! method.


Need Your Help

How to split one file into multiple files using perl?

regex perl file-io split

I have the file as ftp.txt which contains many versions of lines such as

Implementing Security questions

ruby-on-rails devise

I am using devise for the signin process.