如何根据模型名称和属性值向所有 simple_form 输入添加自定义属性?

How to add custom attribute to all simple_form input based on model name and attribute value?

我想为 simple_form 生成的每个输入添加自定义属性。属性值基于模型名称和字段。所以我这样做了:

# app/inputs/base.rb
class Base < SimpleForm::Inputs::Base
  def input_html_options
    super['custom-attr'] = "#{object_name}.#{attribute_name}"
  end
end

这是行不通的。代码根本没有被加载执行。我在这里遗漏了什么吗?

您应该在 lib/simple_form/inputs/base.rb 中添加代码,代码应如下所示以确保它可以自动加载

module SimpleForm
  module Inputs
    class Base
      def input_html_options
        @input_html_options...
      end
    end
  end
end

或像这样在 config/initializers/simple_form_ext.rb 中使用 class_eval

SimpleForm::Inputs::Base.class_eval do
  def input_html_options
    @input_html_options[:'custom-attr'] = "#{object_name}.#{attribute_name}"
    @input_html_options
  end
end