How to allow my model to accept two different date formats?

I am using Ruby on Rails 5. I have the following code in my model ...

class User < ActiveRecord::Base ... attr_accessor :dob_string def dob_string @dob_string || (self.dob ? self.dob.strftime('%m/%d/%Y') : "") end def dob_string=(dob_s) date = dob_s && !dob_s.empty? ? Date.strptime(dob_s, '%m/%d/%Y') : nil self.dob = date rescue ArgumentError errors.add(:dob, 'The birth date is not in the correct format (MM/DD/YYYY)') @dob_string = dob_s end 

Despite my instructions, sometimes users enter a date in the form MM-DD-YYYY. Therefore, I want my model to accept both MM / DD / YYYY or MM-DD-YYYY formats, but not mixed, that is, MM / DD-YYYY shoud is still illegal. How to change my model so that it can accept any format?

+6
source share
1 answer

I think this can do what you need:

 class User < ActiveRecord::Base def dob_string @dob_string || (dob ? dob.strftime("%m/%d/%Y") : "") end def dob_string=(dob_s) unless convert_preferred_date(dob_s) || convert_acceptable_date(dob_s) errors.add(:dob, 'The birth date is not in the correct format (MM/DD/YYYY)') @dob_string = dob_s end end private def convert_preferred_date(dob_s) convert_date(dob_s, "%m/%d/%Y") end def convert_acceptable_date(dob_s) convert_date(dob_s, "%m-%d-%Y") end def convert_date(dob_s, format) self.dob = (dob_s && !dob_s.empty? ? Date.strptime(dob_s, format) : nil) rescue ArgumentError nil end end 

This is a little inelegant, but I can't think of a way to make only two date formats. If you are ready to accept any format of human readable data, there is a much simpler way to do this.

Test this in your application. I just messed around with this in the Rails console, and I may not have tested every case. Hope this helps.

0
source

Source: https://habr.com/ru/post/1015153/


All Articles