mardi 6 janvier 2015

Assign variable as either output of equation OR nil if equation can't run (circumventing NoMethodError)

I'm saving an object as such:



@rentalrequest = RentalRequest.new do |rr|
rr.delivery_start = Time.zone.parse(request_params[:deliverydate] + " " + request_params[:deliverytime_start]).utc
...
end


Every once in a while, my front end validation fails, and somehow, the form is posted even though deliverydate and deliverytime_start are blank. In this case, the controller breaks with a NoMethodError because this statement doesn't make sense: Time.zone.parse("")


However, rather than having to write a rescue for when this happens, I feel like it's so much easier if I can just say rr.delivery_start = nil if Time.zone.parse doesn't work. That way, the back end validation on the @rentalrequest object kicks in and serves as a rescue.


But I'm not sure how to write the rr.delivery_start = nil if Time.zone.parse doesn't work (like... if any part of it doesn't work)


Thoughts?


Aucun commentaire:

Enregistrer un commentaire