When you need to incorporate a datetime picker in a Rails 5 application, you can use the
flatpickr_rails gem. It’s based around flatpickr, a project with 10,000+ stars on GitHub, requires no dependencies, and has well-documented configuration options. Not to mention a polished design and multiple themes.
Here’s how to incorporate it in your Rails 5 application:
1. If you haven’t already, run a migration to generate a field with the type of
datetime. Then run
flatpickr_rails to your Gemfile.
4. Add this line to app/assets/stylesheets/application.css:
*= require flatpickr
//= require flatpickr
6. Restart your server.
7. Add your input field to the form. Change
foo to the name of your input, and
bar to the ID you want to use to create flatpickr’s instance in the next step.
<div class="field"> <%= form.label :foo %><br> <%= form.text_field :foo, id: 'bar' %> </div>
8. Add your JS. Change
bar to your ID from Step 7.
If you want to configure flatpickr, pass a configuration object as the second param:
9. The Rails database saves in the UTC format (i.e. 2019-01-01 15:00:00 -0400), but your users would punch you in the face if you used that, so let’s make it easier to read. Let’s also apply a minimum date of
today and a default minute/hour.
And that’s it. You’re done.1
You might want to change the default timezone for ActiveRecord depending on your application’s needs. For instance, I’m building an application for a local business that, by regulation, can only serve customers in Eastern time, so I decided it’d be good to change the defaults. You can read about doing this here (it’s very easy). ↩︎