所以,我最终解决了这个问题,以下是完整的解决方案。据我了解,由于我使用的是 Rails 2.3,因此没有帮助程序来支持data
前缀属性。事实证明,正如这个答案options_for_select
所指出的那样,我需要使用 Rails 3助手。作为旁注,我没有使用 msDropDown 插件,而是最终使用了ddSlick。另外,我没有使用 ,而是使用了. 那么基本上你必须拥有的是:collection_select
select_tag
rails_overrides.rb
# https://stackoverflow.com/a/13962481/914874
module RailsOverrides
def options_for_select(container, selected = nil)
return container if String === container
container = container.to_a if Hash === container
selected, disabled = extract_selected_and_disabled(selected)
options_for_select = container.inject([]) do |options, element|
html_attributes = option_html_attributes(element)
text, value = option_text_and_value(element)
selected_attribute = ' selected="selected"' if option_value_selected?(value, selected)
disabled_attribute = ' disabled="disabled"' if disabled && option_value_selected?(value, disabled)
options << %(<option value="#{html_escape(value.to_s)}"#{selected_attribute}#{disabled_attribute}#{html_attributes}>#{html_escape(text.to_s)}</option>)
end
options_for_select.join("\n").html_safe
end
def option_text_and_value(option)
# Options are [text, value] pairs or strings used for both.
case
when Array === option
option = option.reject { |e| Hash === e }
[option.first, option.last]
when !option.is_a?(String) && option.respond_to?(:first) && option.respond_to?(:last)
[option.first, option.last]
else
[option, option]
end
end
def option_html_attributes(element)
return "" unless Array === element
html_attributes = []
element.select { |e| Hash === e }.reduce({}, :merge).each do |k, v|
html_attributes << " #{k}=\"#{ERB::Util.html_escape(v.to_s)}\""
end
html_attributes.join
end
end
application_helper.rb
module ApplicationHelper
include RailsOverrides
end
index.html.erb
<%= select_tag(:state, options_for_select (states.map { |state| [state.name, state.code, {"data-imagesrc" => image_path("flags/#{state.code}.png"), "data-description" => "Data from #{state.name}"}]}, current_state.code)) %>
这里,current_state
是要选择作为默认选项的状态。例如,我将它存储在一个session
变量中,但为了简单起见,它可能是一个@current_state
.
解决此问题的另一种方法是使用options_from_collection_for_select_with_data的修改版本,因此无需公开map
.