Attributes filter

Lucas Mazza edited this page Jan 27, 2013 · 1 revision

Attributes filter

In some cases it can be needed to display only some subset of attributes, filtering out others. Usually this task is performed by putting some logic into view. But there is a better way: it is possible to pass a list of attributes to display to simple_form builder. This list can be set in a controller, but to keep this example simple, here it will be set in the view:

<%= filtered_form_for(@topic, display_only: [:name]) do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">
    <%= f.input :name %>
    <%= f.input :sticky %>
  </div>

  <div class="form-actions">
    <%= f.button :submit %>
  </div>
<% end %>

As you can see, filtered_form_for was called instead of simple_form_for. That's because simple_form does not support parameters filtering. However, filtering support can be implemented with a very small amount of code:

# A specific form builder to deal with filtering attributes out based on parameters
class StrongParametersFormBuilder < SimpleForm::FormBuilder
  def input(attribute_name, *args, &block)
    display_filter = self.options[:display_only]

    if display_filter
      super if display_filter.include?(attribute_name)
    else
      super
    end
  end
end

module ApplicationHelper
  # Form Helper to be used
  def filtered_form_for(object, options = {}, &block)
    simple_form_for(object, options.merge(:builder => StrongParametersFormBuilder), &block)
  end
end

Put this code into app/helpers/application_helper.rb, and filtered_form_for will work!

Sample application

https://github.com/denispeplin/display_filter_demo

Credits

Implemented by @carlosantoniodasilva

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.