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.
This commit is contained in:
@@ -33,7 +33,17 @@ class Poll < ApplicationRecord
|
|||||||
belongs_to :budget
|
belongs_to :budget
|
||||||
|
|
||||||
validates_translation :name, presence: true
|
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,
|
validates :starts_at,
|
||||||
comparison: {
|
comparison: {
|
||||||
greater_than_or_equal_to: ->(*) { Time.current },
|
greater_than_or_equal_to: ->(*) { Time.current },
|
||||||
@@ -175,12 +185,6 @@ class Poll < ApplicationRecord
|
|||||||
Poll::Voter.where(poll: self, user: user, origin: "web").exists?
|
Poll::Voter.where(poll: self, user: user, origin: "web").exists?
|
||||||
end
|
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
|
def start_date_change
|
||||||
if will_save_change_to_starts_at?
|
if will_save_change_to_starts_at?
|
||||||
if starts_at_in_database < Time.current
|
if starts_at_in_database < Time.current
|
||||||
|
|||||||
@@ -24,12 +24,14 @@ describe Poll do
|
|||||||
poll.starts_at = nil
|
poll.starts_at = nil
|
||||||
|
|
||||||
expect(poll).not_to be_valid
|
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
|
end
|
||||||
|
|
||||||
it "is not valid without an end date" do
|
it "is not valid without an end date" do
|
||||||
poll.ends_at = nil
|
poll.ends_at = nil
|
||||||
|
|
||||||
expect(poll).not_to be_valid
|
expect(poll).not_to be_valid
|
||||||
|
expect(poll.errors[:ends_at]).to eq ["can't be blank"]
|
||||||
end
|
end
|
||||||
|
|
||||||
it "is not valid without a proper start/end date range" do
|
it "is not valid without a proper start/end date range" do
|
||||||
|
|||||||
Reference in New Issue
Block a user