I have a form that uses jQuery datepicker for picking just the month and year.
$(".date-input").datepicker({
format: 'mm-yyyy',
startView: "months",
minViewMode: "months"
});
I have postgreSQL db on the backend with datetime column storing this date which apparently needs date in full format 'dd-mm-yyyy' to save it. While POSTing the form to my controller, this is what i came across:
Experience.update(date_from: '02-2016')
updates the table with nil value for date_from column
So, the question is how can i append '01-'
into this date_from param that i receive from POST request on the controller as Strong parameters.
Use the ISO8601 Date format (2016-10-21).
$(".date-input").datepicker({
format: 'yyyy-mm-dd',
startView: "months",
minViewMode: "months"
});
You can parse it with Date.iso8601(str)
or DateTime.iso8601(str)
.
I would create a model level setter which handles this:
class Experience < ActiveRecord::Base # or ApplicationRecord
def date_from=(val)
super( val.is_a?(String) ? Date.iso8601(val) : val )
end
end
This means you don't have to worry about the params on the controller level. Just whitelist it like any other scalar value and let your model do the work.
I would just store the values as a DATE type (as the first day of the month). Thats gives you the maximum flexibility when comes to DB querying and also a sane format when you pull records so that you don't have to parse a string again.