Let's put an end to datepicker suffering! Follow this steps to have your shiny new datepicker working in no time! (and remind yourselves of JS plugins in Rails)
Note: We recommend using Bootstrap Datepicker (try your own luck with anything different and remember, jQuery-UI's datepicker sucks, don't use it). These are the only three links you need:
Now, some ancient history you had during lectures on frontend and frontend setup in Rails. What do we need to setup any JS thing in our app?
- JS code (obviously). Where is it? Well, how about the gem?
# Gemfile
gem 'bootstrap-datepicker-rails'
- Rails has a fancy little thing called Assets Pipeline, everything should be "registered" there. That means, requiring JS and CSS parts of our plugin
JS:
# application.js
//= require bootstrap-datepicker <--- add this line right after bootstrap and jquery, right before //=require tree .
CSS:
# application.scss
@import "bootstrap-datepicker"; <--- don't forget the semicolon
- NOT DONE YET! What about actually making our datepicker work in forms? Create a file named
init_datepicker.js
in yourapp/assets/javascripts
. Put this inside:
$('.datepicker').datepicker({
<-- you can pass options here! Get them on the demo page by playing with settings
});
- Step 3 means that datepicker will be activated on any text input field that has a
datepicker
class on it. With simple form:
# your form view
<%= simple_form_for @thing_that_has_a_date_attribute do |f| %>
<%= f.input :date, as: :string, input_html: { class: 'datepicker' } %>
<%= f.button :submit %>
<% end %>
P.S. This sequence of steps is easily adoptable to any JS plugin, remember they should (ideally) all have:
- a gem (google for "NAME_OF_YOUR_PLUGIN Assets Pipeline")
- a way to be present in
application.js
- a way to be present in
application.scss
- a way to initialize themselves (probably creating a new file in
assets/javascripts
is in order) - a way to hook onto elements in your DOM (classes, ids on that elements that an initializer will recognize)
How do you get it back to format date in your controler ?
I had to give the following option
in order to
Date.parse(params[:date])
Is there a lighter way you'd recommend ?