From 33a46ffce8a3f42047ce0ac4980699a659c52f40 Mon Sep 17 00:00:00 2001 From: Nicholas Hippenmeyer Date: Sat, 19 Dec 2020 05:58:40 -0800 Subject: [PATCH] Select field selected value (#1844) When using the select field for a boolean attribute that can be either `true`, `false` or `nil`, the current behavior causes `false` and `nil` to be treated the same. If the attribute is set to `false`, the edit dashboard shows the selected value as being the `nil` option instead of `false` as expected. --- app/views/fields/select/_form.html.erb | 4 +- .../views/fields/select/_edit_spec.rb | 40 +++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 spec/administrate/views/fields/select/_edit_spec.rb diff --git a/app/views/fields/select/_form.html.erb b/app/views/fields/select/_form.html.erb index 5d036c73c4..1e9960c0a5 100644 --- a/app/views/fields/select/_form.html.erb +++ b/app/views/fields/select/_form.html.erb @@ -26,7 +26,7 @@ to be displayed on a resource's edit form page. field.selectable_options, :last, :first, - field.data.presence, + field.data, ) ) %> <% else %> @@ -36,7 +36,7 @@ to be displayed on a resource's edit form page. field.selectable_options, :to_s, :to_s, - field.data.presence, + field.data, ) ) %> <% end %> diff --git a/spec/administrate/views/fields/select/_edit_spec.rb b/spec/administrate/views/fields/select/_edit_spec.rb new file mode 100644 index 0000000000..c5d09aceb5 --- /dev/null +++ b/spec/administrate/views/fields/select/_edit_spec.rb @@ -0,0 +1,40 @@ +require "rails_helper" +require "administrate/field/select" + +describe "fields/select/_form", type: :view do + it "displays the selected option" do + customer = build(:customer) + select = instance_double( + "Administrate::Field::Select", + attribute: :email_subscriber, + data: false, + selectable_options: [true, false, nil], + ) + + render( + partial: "fields/select/form.html.erb", + locals: { field: select, f: form_builder(customer) }, + ) + + expect(rendered).to have_css( + %{select[name="customer[email_subscriber]"] + option[value="false"][selected="selected"]}, + ) + end + + def form_builder(object) + ActionView::Helpers::FormBuilder.new( + object.model_name.singular, + object, + build_template, + {}, + ) + end + + def build_template + Object.new.tap do |template| + template.extend ActionView::Helpers::FormHelper + template.extend ActionView::Helpers::FormOptionsHelper + end + end +end