-
Notifications
You must be signed in to change notification settings - Fork 0
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
endPut this code into app/helpers/application_helper.rb, and filtered_form_for will work!
https://github.com/denispeplin/display_filter_demo
Implemented by @carlosantoniodasilva