Rails: Date Confirmation More Than Other

I am writing a special validator in ActiveRecord, so the deadline makes sense:

  validate :deadline_is_possible?

  def deadline_is_possible?
    if deadline > begins_at
      errors.add(:deadline, 'must be possible')
    end
  end

However, this raises the NoMethodError: undefined `> 'method for nil: NilClass. The event I tried to include dates in strings, for example:

  def deadline_is_possible?
    if deadline.to_s > begins_at.to_s
      errors.add(:deadline, 'must be possible')
    end
  end

and although it does not generate an error, it does not work.

I also declared other validators (e.g.

  def begins_at_is_date?
    if !begins_at.is_a?(Date)
      errors.add(:begins_at, 'must be a date')
    end
  end

which work fine.

+5
source share
3 answers

You may have to contact if one of the dates is zero. You can either set them to the default value in the deadline database, or do something like:

  validate :deadline_is_possible?

  def deadline_is_possible?
    return if [deadline.blank?, begins_at.blank?].any?
    if deadline > begins_at
      errors.add(:deadline, 'must be possible')
    end
  end
+4
source

, deadline . , , .

irb(main):001:0> nil > Date.new
NoMethodError: undefined method `>' for nil:NilClass
+1

:

class AfterDateValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    return if value.blank?

    other_date = record.public_send(options.fetch(:with))

    return if other_date.blank?

    if value < other_date
      record.errors.add(attribute, (options[:message] || "must be after #{options[:with].to_s.humanize}"))
    end
  end
end

:

validates :invited_on, presence: true
validates :selected_on, presence: true, after_date: :invited_on
0

All Articles