Remove blank strings from array report parameters

Remove the blank strings that Rails multiple selects add by default to
make sure that blank lists are still submitted to the server as arrays
instead of nil.

https://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select
This commit is contained in:
Kristina Lim
2018-10-11 11:31:08 +08:00
committed by luisramos0
parent 6e03ab03f5
commit 418050c1b8
3 changed files with 35 additions and 0 deletions

View File

@@ -5,6 +5,7 @@ module OpenFoodNetwork
extend ActiveModel::Naming
extend ActiveModel::Translation
include ActiveModel::Validations
include ActiveModel::Validations::Callbacks
def initialize(attributes = {})
attributes.each do |key, value|

View File

@@ -15,6 +15,8 @@ module OrderManagement
attr_accessor :start_at, :end_at, :distributor_ids, :producer_ids, :order_cycle_ids,
:enterprise_fee_ids, :shipping_method_ids, :payment_method_ids
before_validation :cleanup_arrays
validates :start_at, :end_at, date_time_string: true
validates :distributor_ids, :producer_ids, integer_array: true
validates :order_cycle_ids, integer_array: true
@@ -41,6 +43,20 @@ module OrderManagement
errors.add(:end_at, DATE_END_BEFORE_START_ERROR) unless start_at < end_at
end
# Remove the blank strings that Rails multiple selects add by default to
# make sure that blank lists are still submitted to the server as arrays
# instead of nil.
#
# https://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select
def cleanup_arrays
distributor_ids.reject!(&:blank?)
producer_ids.reject!(&:blank?)
order_cycle_ids.reject!(&:blank?)
enterprise_fee_ids.reject!(&:blank?)
shipping_method_ids.reject!(&:blank?)
payment_method_ids.reject!(&:blank?)
end
end
end
end

View File

@@ -21,6 +21,24 @@ describe OrderManagement::Reports::EnterpriseFeeSummary::Parameters do
it { expect(subject).to validate_integer_array(:shipping_method_ids) }
it { expect(subject).to validate_integer_array(:payment_method_ids) }
it "allows integer arrays to include blank string and cleans it up" do
subject.distributor_ids = ["", "1"]
subject.producer_ids = ["", "1"]
subject.order_cycle_ids = ["", "1"]
subject.enterprise_fee_ids = ["", "1"]
subject.shipping_method_ids = ["", "1"]
subject.payment_method_ids = ["", "1"]
expect(subject).to be_valid
expect(subject.distributor_ids).to eq(["1"])
expect(subject.producer_ids).to eq(["1"])
expect(subject.order_cycle_ids).to eq(["1"])
expect(subject.enterprise_fee_ids).to eq(["1"])
expect(subject.shipping_method_ids).to eq(["1"])
expect(subject.payment_method_ids).to eq(["1"])
end
describe "requiring start_at to be before end_at" do
let(:now) { Time.zone.now }