poctek
poctek

Reputation: 256

Model date validation in Rails

I'm building a calendar app and have some problems with date validations. I want to allow the users to make only future events. After adding a custom validator

class Event < ActiveRecord::Base
  belongs_to :user

  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.parse(date) < Time.now
  end
end

That's the params debug

event: !ruby/hash:ActionController::Parameters
  name: New
  date: 08/17/2015
commit: Add
controller: events
action: create

And I get an error: no implicit conversion of nil into String . What's my mistake?

Upvotes: 2

Views: 172

Answers (3)

WeezHard
WeezHard

Reputation: 2022

Try this:

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

You can also look to this: https://github.com/johncarney/validates_timeliness

Upvotes: 0

MZaragoza
MZaragoza

Reputation: 10111

Take a look at http://rubyquicktips.com/post/527621930/check-if-a-time-or-date-is-in-the-past-or-future

time = 2.hours.ago
time.past? #true
time.future? #false

Upvotes: 0

Piotr Kruczek
Piotr Kruczek

Reputation: 2390

Date.parse() expects a string like shown here. If you saved your :date in an approprieate format you should be able to just do

date < Time.now

Upvotes: 1

Related Questions