时间:2015-05-28 13:22:47

标签: postgresql ruby-on-rails-4

我使用此代码在下拉列表中显示了一系列行业:

<%= ff.select :area_of_business_id, Industry.all.map { |x| [x.name, x.id] }, {include_blank: "Select an industry"}, class: 'droplist default-droplist required' %>

我希望列表中的一个特定行业首先出现在下拉列表中,其余行业按字母顺序排在后面。例如,如果我有这个列表:

Airlines

Broadcasting

Chemicals

Entertainment

Insurance

并且,我希望娱乐首先出现,然后我希望将订单更改为:

Entertainment

Airlines

Broadcasting

Chemicals

Insurance

最干净的方法是什么?

2 个答案:

答案 0 :(得分:4)

是的可能如下。假设您在控制器中有一个实例变量:

@option_values = Industry.order("name <> 'Entertainment', name asc")
                         .pluck(:name, :id)

现在做,

<%= ff.select :area_of_business_id, @option_values, {include_blank: "Select an industry"}, class: 'droplist default-droplist required' %>

该部分order("name <> 'Entertainment', name asc")将首先放置name = 'Entertainment'的记录,然后将其余部分放在递减顺序中。

答案 1 :(得分:1)

Rails仅支持time_zones开箱即用的选项优先级。在所有其他情况下,您应该手动使用以下内容:

<% industries = [Industry.find_by(name: 'Entertainment')] + [Industry.where.not(name: 'Entertainment')] %> 
<%= ff.select :area_of_business_id, industries.map { |x| [x.name, x.id] }, {include_blank: "Select an industry"}, class: 'droplist default-droplist required' %>

但我建议在Industry模型中添加额外的字段,以便在列表中指定位置并按此归档排序。