Reputation: 256
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
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
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
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