Rails, datepicker

= form_for @task do |f|
  = f.datetime_field :done_at
  = f.text_field

I thought because done_at should be saved as DateTime, the field should be datetime_field. But text_field works fine.

On top of that, for some browsers (Firefox, I can say) date type of input tag gives you a datepicker on its own (html5 datepicker), and I didn’t want to have them.

<input id="task_done_at" name="task[done_at]" type="datetime" />

Most of all, I watched an episode of Railscasts and that’s why I started working on it.

I used jquery-ui-sass-rails gem.

I put this file app/assets/javascripts/tasks.js.coffee as following the screencast #213

jQuery ->
  $('#task_done_at').datepicker
    dateFormat: 'yy-mm-dd'

also after setting up

gem 'jquery-ui-sass-rails'

//= require jquery.ui.all
//= require jquery.ui.datepicker

@import jquery.ui.core
@import jquery.ui.theme
@import jquery.ui.datepicker

and not use select tag on form template.

= form_for @task do |f|
  = f.datetime_field :done_at

instead of

= form_for @task do |f|
  = f.datetime_select :done_at

And then, I didn’t know how to style the jquery-ui datepicker. By the way (there are other options but) there’s a twitter bootstrap style.

I used bootstrap-datepicker gem.

After setting up

gem 'bootstrap-datepicker-rails'

@import "bootstrap-datepicker3"

//= require bootstrap-datepicker

I did following

f.datetime_field :done_at, "data-provide" => 'datepicker', "data-date-format" => "yyyy-mm-dd"

You don’t have to write a js file, simply add attributes to the input tag. For I didn’t need much, “data-date-format” was useful. At the end I added a format the field (blank in tasks/new form, same format with the datepicker in tasks/:id/edit form.)

f.text_field :done_at, value: f.object.done_at.try(:strftime, "%Y-%m-%d"), "data-provide" => 'datepicker', "data-date-format" => "yyyy-mm-dd"

That was all. Just in case this is my code on Github.

 
38
Kudos
 
38
Kudos

Now read this

Git Merge your next Change

Sometimes when you want to merge changes made in another branch (in some remote) to your master branch. (or any branch supposed to be working) When you trust and it works fine for sure, then it would be quite simple: git merge And also... Continue →