-
Notifications
You must be signed in to change notification settings - Fork 1.3k
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!
https://github.com/denispeplin/display_filter_demo
Implemented by @carlosantoniodasilva
This page was created by the OSS community and might be outdated or incomplete. Feel free to improve or update this content according to the latest versions of SimpleForm and Rails to help the next developer who visits this wiki after you.
Keep in mind to maintain the guides as simple as possible and to avoid additional dependencies that might be specific to your application or workflow (such as Haml, RSpec, Guard and similars).