Spencer Hire
Spencer Hire

Reputation: 763

Time.now validation in rails 4

I'm just looking for an elegant line that can validate my starts_at field in my table. It just needs to validate that the starts_at field in the form is greater than the current time, cheers.

  validates :starts_at, starts_at >= Time.now? 

Upvotes: 0

Views: 198

Answers (2)

Kannan S
Kannan S

Reputation: 2489

I am using 'validates_timeliness' for effective Time validations instead of hard code.

 gem 'validates_timeliness', '~> 3.0'

Refer here: https://github.com/adzap/validates_timeliness

Upvotes: 1

andmcgregor
andmcgregor

Reputation: 485

You can build a custom validation for that. Something like:

class ModelName < ActiveRecord::Base
  validate :time_is_in_future

  def time_is_in_future
    if starts_at < Time.now
      errors.add(:starts_at, "starts_at must be in the future")
    end
  end
end

See: http://guides.rubyonrails.org/active_record_validations.html#custom-validators

Upvotes: 4

Related Questions