gpt4 book ai didi

ruby-on-rails - select_tag helper with grouped_options_for_select order

转载 作者:行者123 更新时间:2023-12-04 03:36:11 28 4
gpt4 key购买 nike

我的模型中有这个:

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

这是在 View 中:
<%= 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 => 'Please select'不起作用

最佳答案

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

 <%= 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.properties 中。
def unsorted_grouped_options_for_select(grouped_options, selected_key = nil, prompt = nil)
body = ''
body << content_tag(:option, prompt, { :value => "" }, 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, options_for_select(group[1], selected_key), :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, nil, "Please Select"), :id => 'location-dropdown' %>

关于ruby-on-rails - select_tag helper with grouped_options_for_select order,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5612274/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com