当前行为
使用simple_form,您需要传递一个数组:
<%= f.input :my_field, collection: [[true,"Yes"],[false,"No"]] %>
预期行为
能够传递散列会很好,因此您不需要对传递的每个散列进行invert.sort。有什么办法可以对每个输入执行此操作吗?
<%= f.input :my_field, collection: {"true"=> "yes", "false"=>"No" } %>
是否可以在没有invert.sort?
的情况下将哈希直接传递到输入中?
答案 0 :(得分:1)
您可以添加自己的助手my_simple_form_for
来使用自己的YourFormBuilder
module ApplicationHelper
def my_form_for record, options = {}, &block
options[:builder] = MyFormBuilder
simple_form_for(record, options, &block)
end
end
或者以这种方式使用它:
<%= simple_form_for @record, builder: MyFormBuilder do |f| %>
在您自己的构建器中,您可以覆盖input
:
class YourFormBuilder < SimpleForm::FormBuilder
def input(attribute_name, options = {}, &block)
options[:collection] = options[:collection].invert.sort if options[:collection].present? and options[:collection].kind_of? Hash
super
end
end
答案 1 :(得分:0)
基于我们的earlier Q&A,您可以增强Hash
扩展名使其包含as_select_options
:
module DropdownExt
def self.extended(receiver)
receiver.each do |k,v|
define_method(k) do
v.is_a?(Hash) ? v.extend(DropdownExt) : v
end
end
define_method(:as_select_options) do
unless receiver.values.map{|v|v.class}.include?(ActiveSupport::HashWithIndifferentAccess)
receiver.invert.sort
else
[]
end
end
end
end
class Dropdowns
class << self
private
def dropdowns_spec
YAML.load_file("#{path}").with_indifferent_access
end
def path
Rails.root.join("spec/so/dropdowns/dropdowns.yaml") # <== you'll need to change this
end
end
dropdowns_spec[:dropdown].each do |k,v|
define_singleton_method k do
v.extend(DropdownExt)
end
end
%i(
truck_model
bike_model
).each do |to_alias|
singleton_class.send(:alias_method, to_alias, :car_model)
end
end
哪个可以让您执行以下操作:
Dropdowns.car_model.field1.as_select_options
=> [["false", "no"], ["true", "yes"]]
或者,我想:
<%= f.input :my_field, collection: Dropdowns.car_model.field1.as_select_options %>
这不能避免invert.sort
。但是,它确实将其掩埋了一点并用方便的as_select_options
方法将其包装起来。