Search code examples
ruby-on-rails-4simple-form

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


I want to add a custom attribute to every input generated by simple_form. The attribute value is based on model name and field. So I did this:

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

This isn't working. The code is not being loaded for execution at all. Am I missing something here?


Solution

  • you should add code in lib/simple_form/inputs/base.rb, code should look like this to make sure it can be loaded automatically

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

    or use class_eval in config/initializers/simple_form_ext.rb like this

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