Jensky
Jensky

Reputation: 917

Only future dates - validation in Rails model

I have field date in the User model. It shuld have only future dates (from registration moment). What is the best way to validation it in the model?

I think about something like this:

class User < ActiveRecord::Base
  validates :name, presence: true
  validates :date, presence: true
  validate :future_event


  private

  def future_event
    errors.add(:date, "Can't be in the past!") if date < Time.now
  end
end

Is it OK?

Can you think about some more simple and elegant solution?

Upvotes: 3

Views: 4012

Answers (3)

Joshua Pinter
Joshua Pinter

Reputation: 47471

Use inclusion.

Something like this:

validates :date, inclusion: { in: Proc.new{ 1.day.from_now.. }, message: "has to be in the future" }

Upvotes: 0

John Naegle
John Naegle

Reputation: 8247

Take a look at the Date Validator Gem

validates :start_date,
  date: { after: Proc.new { Date.current }, message: 'must be after today' },
  on: :create

You might always want to investigate the differences between Date.current and Date.today - Date.current is timezone aware and will use the Timezone of your Rails app. Date.today uses system time. There can be odd differences if one is UTC and one is Eastern.

Upvotes: 3

max
max

Reputation: 101811

# lib/future_validator.rb
class FutureValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    if record[attribute] < Time.now
      record.errors[attribute] << (options[:message] || "can't be in the past!")
    end
  end
end

class User < ActiveRecord::Base
  validates :name, presence: true
  validates :date, presence: true
  validates :future_event, future: true
end

Upvotes: 5

Related Questions