From 01ce3c957674c90b6d1fda713bb40587d7e8c02d Mon Sep 17 00:00:00 2001 From: Cadu Ribeiro Date: Fri, 18 Aug 2023 11:27:27 -0300 Subject: [PATCH] Add include_blank option to enum field Currently the field only renders the blank option if there is no presence validator on the specific field. But there is a problem with this approach because you can have the validator field but with some condition like: validates :matrimonial_regime, presence: true, if: :married? and the field was being rendered without the blank option. This commit adds a new `include_blank` that can be set into enum field to force a blank field to be present. --- app/views/fields/enum/_form.html.erb | 2 +- lib/administrate/field/enum.rb | 4 ++++ spec/lib/administrate/field/enum_spec.rb | 18 ++++++++++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/app/views/fields/enum/_form.html.erb b/app/views/fields/enum/_form.html.erb index 68c8b96..46c5faf 100755 --- a/app/views/fields/enum/_form.html.erb +++ b/app/views/fields/enum/_form.html.erb @@ -26,6 +26,6 @@ By default, the input is a select field for the enum attributes. end, f.object.public_send(field.attribute.to_s) ), - { include_blank: !f.object.class.validators_on(field.attribute.to_s).map(&:class).include?(ActiveRecord::Validations::PresenceValidator) }, + { include_blank: field.include_blank_option || !f.object.class.validators_on(field.attribute.to_s).map(&:class).include?(ActiveRecord::Validations::PresenceValidator) }, field.html_options) %> diff --git a/lib/administrate/field/enum.rb b/lib/administrate/field/enum.rb index fb9815d..050f906 100755 --- a/lib/administrate/field/enum.rb +++ b/lib/administrate/field/enum.rb @@ -12,6 +12,10 @@ def html_options options[:html] || {} end + def include_blank_option + options.fetch(:include_blank, false) + end + class Engine < ::Rails::Engine end end diff --git a/spec/lib/administrate/field/enum_spec.rb b/spec/lib/administrate/field/enum_spec.rb index d2fc746..cf378f8 100755 --- a/spec/lib/administrate/field/enum_spec.rb +++ b/spec/lib/administrate/field/enum_spec.rb @@ -12,6 +12,24 @@ end end + describe '.include_blank' do + it 'is false by default' do + page = :show + + field = Administrate::Field::Enum.new(:status, 'status', page) + + expect(field.include_blank_option).to be_falsy + end + + it 'can override include_blank_option' do + page = :show + + field = Administrate::Field::Enum.with_options(include_blank: true).new(:status, 'status', page) + + expect(field.include_blank_option).to be_truthy + end + end + describe '#html_options' do it 'returns a hash of :html options' do page = :show