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

레일스로 코딩 배우기

나는 루비가 코딩을 배우기에 좋은 출발점이라고 생각한다 Learn To Program 이라는 책을 읽어보라 https://pine.fm/LearnToProgram/ 물론 어느 programming language 로 시작하든지 코딩을 배우는 것은 인생에서 매우 중요하다고 생각한다 그리고 루비를 배우기에는 레일스가 좋은 출발점이라고 생각한다 지금 시작해보자 rails new app_name cd app_name 레일스의... Continue →