DEV Community

Discussion on: Rails: The Quick-and-Dirty to February 31

Collapse
 
jkt779 profile image
Michael • Edited

Great that you're creative with your workaround :)!

Another way could be a model validation that adds an error to the instance instead of parsing an invalid date to a unintended one. For example, you could use a custom validation like this:

# in user.rb model

validate :ensure_birthdate_format, if: -> { birthdate.present? }

# ...

private

def ensure_birthdate_format
  birthdate_before_type_cast.to_date
rescue ArgumentError
  errors.add(:birthdate, :invalid)
end
Enter fullscreen mode Exit fullscreen mode
Collapse
 
hiddencilantro profile image
Joohyun "Steve" Kim

Oh you put me to shame Michael! You're right, I could definitely move this to the model and write a custom validation. Quick question though, won't _before_type_cast return a hash? I'm not sure if I'd be able to call #to_date on it. But I suppose I could just pass the values into a Date object again and rescue the error. Either way, it's a great idea to keep this logic out of the controller! Thank you!