अतिरिक्त विशेषता हैश केवल रेल 3 में समर्थित है।
यदि आप 2.x रेल पर हैं , और ओवरराइड करना चाहते हैंoptions_for_select
मैं मूल रूप से सिर्फ रेल 3 कोड की नकल करता हूं। आपको इन 3 विधियों को ओवरराइड करने की आवश्यकता है:
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
Kinda गन्दा लेकिन यह एक विकल्प है। मैं इस कोड को एक सहायक मॉड्यूल में रखता RailsOverridesहूं जिसे मैं तब शामिल करता हूं ApplicationHelper। आप चाहें तो एक प्लगइन / मणि भी कर सकते हैं।
एक गोटा यह है कि इन तरीकों का लाभ उठाने के लिए आपको हमेशा options_for_selectसीधे आह्वान करना चाहिए । शॉर्टकट पसंद है
select("post", "person_id", Person.all.collect {|p| [ p.name, p.id, {"data-stuff"=>"html5"} ] })
पुराने परिणाम देगा। इसके बजाय यह होना चाहिए:
select("post", "person_id", options_for_select(Person.all.collect {|p| [ p.name, p.id, {"data-stuff"=>"html5"} ] }))
फिर से एक महान समाधान नहीं है, लेकिन यह कभी भी इतना उपयोगी डेटा-विशेषता प्राप्त करने के लिए इसके लायक हो सकता है।