I’m trying to render a Date field for my rails model as a datepicker.
The model looks like:
class Appointment
include Mongoid::Document
field :date, type: Date
end
_form.html.haml view looks like:
= form_for @appointment, :url => {:action => :create} do |f|
= f.text_field(:date, {:class => 'datepicker'})
%button{:type => 'submit'} Book appointment
:javascript
jQuery(document).ready(function($) {
$('.datepicker').datepicker();
});
Controller action looks like:
class AppointmentsController < ApplicationController
def create
@appointment = Appointment.new(params[:appointment])
# rest left out for demo purposes
end
end
When “new” gets, called an error occurs:
ArgumentError in AppointmentsController#create
argument out of range
I know the value gets posted as MM/DD/YYYY, i.e. 03/11/2013
How can I tell Rails how to properly serialize this field?
Figured it out. I added another field, date_string just as an attr_accessor that won’t get stored in the db but can surface to the form, and can be used to convert to the internal date field. The model is changed to be:
In the view, the date_string field is used:
This works correctly and I’ve verified the field gets set in the db correctly.