Rails select_tag 按字母顺序排序

4
我有这个 select_tag
select_tag :id, options_for_select(Portal.all.collect{|p| [p.name, portal_datum_path(p.id)]}, [@portal.name, portal_datum_path(@portal)]), :onChange => "window.location=($(this).val());"

它允许用户选择一个门户网站来查看我想要显示的某些元素,我希望按字母顺序显示这些门户网站。

我尝试在控制器中按:name排序,但没有成功。

def index
  @portals = Portal.with_name_or_subdomain(params[:keyword]).order(:name).limit(100)
end

我看了Rails文档,发现select_tag本身没有内置选项,是否有一些秘密选项可以使用?

4个回答

6

一小时后,您需要做的就是对传递给options_for_select的选项数组进行排序。这是我的hack方法,虽然可以解决问题,但并不十分优雅。

select_tag :id, options_for_select(Portal.all.collect{|p| [p.name, portal_datum_path(p.id)]}.sort, [@portal.name, portal_datum_path(@portal)]), :onChange => "window.location=($(this).val());"

希望这能有所帮助。

1
将您的选项收集到一个数组中,就像您已经做的那样:
options = Portal.all.collect{|p| [p.name, portal_datum_path(p.id)]},    [@portal.name, portal_datum_path(@portal)])

然后进行排序:

options.sort!{ |x, y| x[0] <=> y[0] }

我在options_for_select的猴子补丁中实现了这个功能,它是我构建的一个模块的一部分,用于处理各种选择内容,因为像这样对选择进行排序比不排序更常见。
def options_for_select(options, selected_items:nil, alphabetize: true)
  options.sort!{ |x, y| x[0] <=> y[0] } if alphabetize 
  super(options, selected_items)
end

1

将其更改为

select_tag :id, options_from_collection_for_select(portals,:name, :id, 1), :onChange => "window.location=($(this).val());"**强调文本**

0

试试这个:

select_tag :id, options_for_select(Portal.all.order(name: :asc).collect{|p| [p.name, portal_datum_path(p.id)]}.sort, [@portal.name, portal_datum_path(@portal)]), :onChange => "window.location=($(this).val());"

1
你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心找到有关如何编写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接