Mike
Mike

Reputation: 67

Rails How to validate time and date

Hi Im stil trying to do a little Restaurant-Website in Ruby on Rails(v. 3.2.13).

Here you can see my current configuration: How to use params in another action?

Right now it is possible to book a table, but there is no validation. I think i have to validate the start-time, the end-time and the date in the form_tag like the following:

Ok End-time should not be validated. Every reservation lasts 2 hours so I just have to allocate the value Start-time+2 hours.

I tried it with the time_selectand date_select but the format looks very odd (5i,4i,...) and I couldnt do anything with this.

Should I use gem for validation? Is it possible to sum times(Start-time +2 hours)? Can I use another format for time/date? Did i forget any further aspects to validate?

I dont know how to continue. Thanks

Upvotes: 1

Views: 6180

Answers (3)

scarver2
scarver2

Reputation: 7995

Checkout validates_timeliness gem It keeps your models clean and intuitive and supports I18n localization with flexible error messages for various date/time comparisons.

validates_datetime :starts_at, :after => :now
validates_datetime :ends_at, :on_or_after => :two_days_later, :if => :starts_at

def two_days_later
  self.starts_at + 2.hours
end

Upvotes: 1

dirtydexter
dirtydexter

Reputation: 1073

k i finally did it with Regex

t=params[:Starttime].scan(/\d\d/)
my_time = t[0] << ":" << t[1] << ":00"
Time.zone.parse(my_time)

this is the ref to the Time.zone.parse this will finally give you the time object that you want.
Please notify me if it worked for you.

Upvotes: 2

dirtydexter
dirtydexter

Reputation: 1073

You can change the defult format that is given by the form from which you have picked the date using this parse function and it will return you a date object in ruby. then you can apply all the validations you want very easily.

 Date.parse(yourDate.to_s)

for checking in future there is a direct method as date_object.future? so you can check with that. and yeah it is possible to sum times in rails you can do your_time + 2.hours for adding 2 hours to the time.

Upvotes: 0

Related Questions