【问题标题】:Rails select_tag alphabetical orderRails select_tag 按字母顺序
【发布时间】:2022-01-19 10:55:06
【问题描述】:

我有这个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 本身没有内置选项,是否有一些我应该使用的秘密选项?

【问题讨论】:

    标签: ruby-on-rails html-select


    【解决方案1】:

    一小时后,您所要做的就是.sort 传递给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());"
    

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      改成

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

      【讨论】:

        【解决方案3】:

        将您的选项收集到一个数组中,就像您所做的那样:

        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
        

        【讨论】:

          【解决方案4】:

          试试这个:

          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());"
          

          【讨论】:

          • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-10-07
          • 2011-09-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-11-08
          相关资源
          最近更新 更多