Working on current projects, I found it necessary to create tens of date form fields. The View part is the weekest among MVC in Rails in comparition to other frameworks (Grails…), so it is quite obvious I looked for some helper. The best I have found is Formtastic. I have found a very DRY soultion to add new filed type to formtastic, that would automatically integrate this filed with jQuery UI datepicker.
Step-by-step manual
1. Download jQuery and jQuery UI and include them to your layout with javascript_include_tag and stylesheet_link_tag.
2. I assume you have formtastic gem installed. Then go to Configuration/Initializers/formtastic.rb and add the following lines in the beginning of the file:
module Formtastic module DatePicker protected def datepicker_input(method, options = {}) format = options[:format] || ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS[:default] || '%d %b %Y' string_input(method, datepicker_options(format, object.send(method)).merge(options)) end # Generate html input options for the datepicker_input # def datepicker_options(format, value = nil) datepicker_options = {:value => value.try(:strftime, format), :input_html => {:class => 'ui-datepicker'}} end end end Formtastic::SemanticFormBuilder.send(:include, Formtastic::DatePicker)
3. Add the following lines to public/javascript/application.js:
$(document).ready(function(){ $('input.ui-datepicker').datepicker(); });
4. Ready! Now you can use a new tag :as => :datepicker inside formtastic tag, as in the following example:
<% semantic_form_for @master do |f| -%> <% f.inputs do -%> <%= f.input :name %> <%= f.input :born, :as => :datepicker %> <% end -%> <%= f.buttons %> <% end -%>
I hope it will help Drop a comment if you have any questions.
Update
Thanks to demersus, there is a plugin integrating jQuery UI datepicker with Ruby on Rails Formtastic — thanks!