简体   繁体   English

Ruby on Rails:下拉菜单中元素的唯一性

[英]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. 我对ROR非常陌生,并且在使下拉菜单中的元素唯一时遇到了问题。 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. 提前致谢。

Rather than calling uniq! 而不是打电话给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! 这样做的好处是可以直接从数据库后端选择唯一的公司作为唯一公司,而不是昂贵地检索所有公司并随后使用uniq对其进行过滤! method. 方法。

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. 但是请注意公司的ID,以及您将如何使用它们。

Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM