简体   繁体   English

将下拉菜单按字母顺序放在红宝石上

[英]Put drop-down menu in alphabetical order in ruby on rails

I'm using ruby on rails to create a database. 我正在使用ruby on rails创建数据库。 I added a drop-down menu for the form of one of my tables. 我为其中一个表格的形式添加了一个下拉菜单。 The drop-down menu is a foreign key from another table. 下拉菜单是来自另一个表的外键。 I'm trying to figure out how to put that drop-down menu in alphabetical order. 我试图弄清楚如何将下拉菜单按字母顺序排列。

Here is my code for form.html. 这是我的form.html代码。

<div class="field">
  <%= f.label :founder_id %><br />
  <%= f.select(:founder_id, @founders.map{|founder| [founder.founder_name, founder.id]}) %>
</div>

Is there anything I can change to get this to show up in my form in alphabetical order? 我有什么可以改变的,可以使其按字母顺序显示在表单中? Any tips would be great. 任何提示都很好。 Thanks! 谢谢!

Yes, just add some sorting: 是的,只需添加一些排序即可:

@founders.sort_by(&:founder_name).map{|founder| [founder.founder_name, founder.id]}

or 要么

@founders.map{|founder| [founder.founder_name, founder.id]}.sort_by(&:first)

f.select will display the options in the same order that it gets them. f.select将以获取选项的顺序显示选项。 Case insensitive sorting is left as an exercise. 不区分大小写的排序作为练习。

@founders.map{|founder| [founder.founder_name, founder.id]}.sort{|a,b| a.founder_name.downcase <=> b.founder_name.downcase}

这将解决您的问题。

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

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