As a somewhat beginner programmer, this problem has bugged me for years. I have a jquery datetime picker that fills in a form field with a date formatted as MM/DD/YYYY
aka 06/27/2015
. Databases won't seem to save the date unless it comes in the YYYY/MM/DD
format. But, despite how my database feels, I like this format because users know how to read it.
So I've got a date in the wrong format when it comes over to my controller. I could use strftime to edit the date before saving it. But I'm lazy in a way, because still want to use strong parameters to create my entry like so.
def create
Statistic.create(statistic_params)
end
def statistic_params
params.require(:statistic).permit(:entry_date)
end
What's the best way to adjust the date format so the database recognizes it and keeps my users happy?
Within your Statistic model, you can change the entry_date
attribute using the before_save
method which will let you change the attribute before saving to the database, so that you don't need to worry about strong parameters.
class Statistic < ActiveRecord::Base
before_validation :set_entry_date
def set_enty_date
self.entry_date = DateTime.strptime(self.entry_date, "%m/%d/%Y").strftime("%Y/%m/%d")
end
end