加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 带有grouped_options_for_select命令的select_

发布时间:2020-12-17 01:49:00 所属栏目:百科 来源:网络整理
导读:我的模型中有这个: LOCATION_IN_UK = {'England' = [['Berkshire',1],['Cambridgeshire',2],['Cheshire',3]],'Scotland' = [['Dumfries and Galloway',4],['Fife',5],['Lothian',6]],'Others' = [['Outside UK',7]]} 这是在视图中: %= select_tag :locatio
我的模型中有这个:

LOCATION_IN_UK = {'England' => [['Berkshire',1],['Cambridgeshire',2],['Cheshire',3]],'Scotland' => [['Dumfries and Galloway',4],['Fife',5],['Lothian',6]],'Others' => [['Outside UK',7]]}

这是在视图中:

<%= select_tag :location,grouped_options_for_select(Location::LOCATION_IN_UK),:id => 'location-dropdown' %>

此代码生成以下html:

<select id="location-dropdown" name="location">
  <optgroup label="England">
    <option value="1">Berkshire</option> 
    <option value="2">Cambridgeshire</option> 
    <option value="3">Cheshire</option></optgroup>
  <optgroup label="Others">
    <option value="7">Outside UK</option></optgroup>
  <optgroup label="Scotland">
    <option value="4">Dumfries and Galloway</option> 
    <option value="5">Fife</option> 
    <option value="6">Lothian</option></optgroup>
</select>

1.如何跳过按字母顺序排序的顺序.我希望元素的位置与哈希LOCATION_IN_UK完全相同.
2.如何在此插入提示? :prompt => ‘请选择’不起作用

解决方法

要回答提示问题,提示不是哈希,它是方法调用的第三个参数.所以你会这样做:

<%= select_tag :location,grouped_options_for_select(LOCATIONS_IN_UK,nil,"Please Select"),:id => 'location-dropdown' %>

看看源代码,似乎没有办法跳过排序.你可以编写自己的帮助方法.这是来源

# File actionpack/lib/action_view/helpers/form_options_helper.rb,line 449
      def grouped_options_for_select(grouped_options,selected_key = nil,prompt = nil)
        body = ''
        body << content_tag(:option,prompt,{ :value => "" },true) if prompt

        grouped_options = grouped_options.sort if grouped_options.is_a?(Hash)

        grouped_options.each do |group|
          body << content_tag(:optgroup,options_for_select(group[1],selected_key),:label => group[0])
        end

        body.html_safe
      end

您可以修改/覆盖该方法,但如果您在其他地方使用此函数,则可能会中断,这就是为什么我建议您将以下内容放在application_helper中.

def unsorted_grouped_options_for_select(grouped_options,prompt = nil)
  body = ''
  body << content_tag(:option,true) if prompt

  ##Remove sort
  #grouped_options = grouped_options.sort if grouped_options.is_a?(Hash)

  grouped_options.each do |group|
    body << content_tag(:optgroup,:label => group[0])
  end

  body.html_safe
end

然后,您可以调用unsorted_grouped_options_for_select,它应该可以工作.

<%= select_tag :location,unsorted_grouped_options_for_select(LOCATION::LOCATION_IN_UK,:id => 'location-dropdown' %>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读