Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rescuing an invalid date in a rails controller

I have this in a controller:

pickuptime = params[:appointment][:pickuptime]
pickuptime = DateTime.strptime(pickuptime, "%m/%d/%Y %l:%M %p %Z")

I would like to rescue it if DateTime.strptime kicks back an Invalid Date error and redirect it back to the previous page with the flash message 'Invalid date'. How can I accomplish this?

I am using Ruby 2.1.2 and Rails 4.1.4. Thanks!

like image 365
jackerman09 Avatar asked Dec 25 '22 23:12

jackerman09


1 Answers

you can do this in your controller:

begin
  pickuptime = params[:appointment][:pickuptime]
  pickuptime = DateTime.strptime(pickuptime, "%m/%d/%Y %l:%M %p %Z")
rescue ArgumentError => e
  flash[:error] = e.message
  redirect_to :back
  return
end

The Invalid Date Error should be a ArgumentError exception with the message you want.

like image 133
Edward Avatar answered Jan 09 '23 03:01

Edward