Ruby on rails 简单表单接受集合输入的哈希
当前行为 使用simple_form,您需要传递一个数组:Ruby on rails 简单表单接受集合输入的哈希,ruby-on-rails,simple-form,ruby-on-rails-5.2,simple-form-for,Ruby On Rails,Simple Form,Ruby On Rails 5.2,Simple Form For,当前行为 使用simple_form,您需要传递一个数组: <%= f.input :my_field, collection: [[true,"Yes"],[false,"No"]] %> 预期行为 如果能够传递一个散列,那就太好了,所以您不需要对传递的每个散列都执行invert.sort。有没有办法对每个输入都这样做 <%= f.input :my_field, collection: {"true"=> "yes", "false"=>"No" } %&
<%= f.input :my_field, collection: [[true,"Yes"],[false,"No"]] %>
预期行为
如果能够传递一个散列,那就太好了,所以您不需要对传递的每个散列都执行invert.sort。有没有办法对每个输入都这样做
<%= f.input :my_field, collection: {"true"=> "yes", "false"=>"No" } %>
“是”、“假”=>“否”}%>
是否可以将哈希直接传递到输入中而不使用invert.sort?
基于我们的,您可以增强哈希
扩展以包括as\u select\u选项
:
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
或者,我想:
<%= f.input :my_field, collection: Dropdowns.car_model.field1.as_select_options %>
它不会避免
反转.sort
。但是,它确实把它埋了一点,并用一种方便的方法将它包装起来。您可以添加自己的帮助程序my\u simple\u form\u以使用自己的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| %>
你的意思是像
{“true”=>“yes”,“false”=>“No”}。对a
?还是你的意思是翻译布尔语?
<%= simple_form_for @record, builder: MyFormBuilder do |f| %>
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