user4133294
user4133294

Reputation:

What's the proper format for the "date" datatype?

My model "User" has a date attribute :birthday. But if I submit a birthday with any format other than x/x/x, it just becomes nil. So, for example, 1/1/1 becomes "0001-01-01", but 1/1/15 becomes nil. 1/1/2 becomes "0001-01-02", but 22/1/3 becomes nil.

I feel like I'm missing something here. It can't possibly be true that date attributes can only be x/x/x, right?

Upvotes: 1

Views: 1263

Answers (1)

Max Williams
Max Williams

Reputation: 32933

How are you setting the date? Is it something like @user.birthday = params[:birthday]? This is going to cause you problems because it's not a date, it's a string, and a string in a different format to how your database stores the date, at that.

You've got two options:

A) Ideally you should convert the input to a date, and then set the field using the actual date object.

B) make sure the format of your parameter matches how your db stores dates (which is "yyyy-mm-dd" by the looks of it).

A is preferable. I would override the User#birthday= method to try to get it to process the date as usefully as possible. eg

#in User model
 def birthday=(arg)
   if arg.is_a?(Date)
     self[:birthday] = arg
   elsif arg =~ /\d+\/\d+\/\d+/
     self[:birthday] = Date.strptime(arg, "%d/%m/%y")
   elsif arg =~ /\d+\-\d+\-\d+/
     self[:birthday] = Date.strptime(arg, "%y/%m/%d")
   else
     self[:birthday] = arg
   end
 end

Upvotes: 1

Related Questions