Give Your Dates: Ruby on Rails 6 With Webpacker
A tutorial to get Bootstrap, jQuery and flatpickr working on Rails 6 with Webpacker.
Join the DZone community and get the full member experience.Join For Free
I wanted to add Bootstrap, then code a form that has two date picker fields and two submit buttons with tool tip text. Pretty simple requirement, right? Ideally, it should have taken me just a few minutes to get it working. But turns out, I had to spend 2-3 hours. In this era of online documentation, Googling and stackoverflowing is an atrocious waste of time. Hence this article, so others can implement similar requirements in just a few minutes.
For the datepicker, I chose flatpickr.
Here are the steps:
- Run the following command in your project folder:
$ yarn add bootstrap jquery popper.js flatpickr
- Create the file application.scss and import the required css files.
- In application.js, add require bootstrap, flatpickr and add event handler actions for the buttons' tooltips and flatpickr instantiation.
- Write some pre-pending jabberwocky in environment.js
- Code the rails form with text_field_tag and submit_tag with proper attributes.
The controller method process_dates checks params[:commit] to find which button was clicked and takes appropriate action. Code blocks for steps 2 - 5 are given below:
For the sake of giving a complete use case, I added a little fun feature. On clicking the first button titled ‘Hist’, the action ‘process_dates’ validates the flatpickr entries for proper dates and then calls curl on the year and date APIs of numbersapi.com to fetch historical events that happened on the date(s). Of course, in the controller action, I do some text manipulation to give a better display on the view.
The second button, titled 'Diff', has very simple functionality: if two valid dates are selected, it just gets the number of days between the two dates.
For those interested in cloud deployment, here is configuration:
Opinions expressed by DZone contributors are their own.