From 00c97ad5879720ac7dcc983b91b8dc562b593ea6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javi=20Mart=C3=ADn?= Date: Fri, 12 Apr 2024 22:47:56 +0200 Subject: [PATCH] Split polls date range validation It was a bit strange to leave the end date blank and have a message associated with the start date, so we're using presence validations instead. For the range validation, we're using the comparison validator included in Rails 7.0. --- app/models/poll.rb | 18 +++++++++++------- spec/models/poll/poll_spec.rb | 4 +++- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/app/models/poll.rb b/app/models/poll.rb index 5fda6f884..8b6ec8624 100644 --- a/app/models/poll.rb +++ b/app/models/poll.rb @@ -33,7 +33,17 @@ class Poll < ApplicationRecord belongs_to :budget validates_translation :name, presence: true - validate :date_range + + validates :starts_at, presence: true + validates :ends_at, presence: true + + validates :starts_at, + comparison: { + less_than_or_equal_to: :ends_at, + message: ->(*) { I18n.t("errors.messages.invalid_date_range") } + }, + allow_blank: true, + if: -> { ends_at } validates :starts_at, comparison: { greater_than_or_equal_to: ->(*) { Time.current }, @@ -175,12 +185,6 @@ class Poll < ApplicationRecord Poll::Voter.where(poll: self, user: user, origin: "web").exists? end - def date_range - if starts_at.blank? || ends_at.blank? || starts_at > ends_at - errors.add(:starts_at, I18n.t("errors.messages.invalid_date_range")) - end - end - def start_date_change if will_save_change_to_starts_at? if starts_at_in_database < Time.current diff --git a/spec/models/poll/poll_spec.rb b/spec/models/poll/poll_spec.rb index 992c7daa7..d88a1277a 100644 --- a/spec/models/poll/poll_spec.rb +++ b/spec/models/poll/poll_spec.rb @@ -24,12 +24,14 @@ describe Poll do poll.starts_at = nil expect(poll).not_to be_valid - expect(poll.errors[:starts_at]).to eq ["Invalid date range"] + expect(poll.errors[:starts_at]).to eq ["can't be blank"] end it "is not valid without an end date" do poll.ends_at = nil + expect(poll).not_to be_valid + expect(poll.errors[:ends_at]).to eq ["can't be blank"] end it "is not valid without a proper start/end date range" do