12
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Rails5 with DatetimePicker

Last updated at Posted at 2019-04-07

Rails5 with DatetimePicker

検索機能実装するにあたり、登録日時(created_at)や更新日時(updated_at)を検索条件としたい場合(それ以外の場合でも)月日をGUIで指定できるDatepickerは有名ですが、時間も指定できるDatetimepickerというものがあり、そちらで実装してみようと思いました。

しかし...

ですが、Rails DatetimepickerでGoogle先生にお伺いたて、検索した結果、Bootstrap3まで対応しているDatetimepickerの記事が多く、Bootstrap4を使っているので、採用できませんでした。

Tempus Dominusの導入

このQiita記事の「Tempus Dominus」を導入します。

Gemfile

Gemfileに以下を追加します。

Gemfile
# bootstrap4
gem 'jquery-rails'
gem 'bootstrap', '~> 4.3.1'

# font-awesome
gem 'font-awesome-rails'

# moment.js
gem 'momentjs-rails'

# Tempus Dominus
gem 'bootstrap4-datetime-picker-rails'
Terminal
$ bundle install

application.js

application.js
//= require jquery3

//= require popper
//= require bootstrap-sprockets

//= require moment
//= require moment/ja.js

//= require tempusdominus-bootstrap-4.js

tempusdominus-bootstrap-4.jsの前にmomentをimportしてください。
(エラーになります。)

application.scss

application.scss
// for Bootstrap4
@import "bootstrap";

// for font-awesome
@import "font-awesome";

// for TempusDominus
@import "tempusdominus-bootstrap-4.css";

js同様、tempusdominus-bootstrap-4.cssの前にbootstrap、font-awesomeをimportしてください。

form.html.erb

実際にformを埋め込むところを以下のように記述

form.html.erb
<div class="input-group" data-target-input="nearest">
    <%= f.text_field :created_at, id: "created_at", class: "form-control datepicker", data: { target: '#created_at'} %>
    <div class="input-group-append" data-target="#created_at" data-toggle="datetimepicker">
        <div class="input-group-text"><i class="fa fa-calendar"></i></div>
    </div>
</div>

jsに以下のように記載

js
<script>
  $(function () {
    $('.datepicker').datetimepicker({
      format: 'YYYY-MM-DD HH:mm:ss'
    });
  });
</script>

formatとして「2019-01-01 00:00:00」を指定しています。

起動

datetimepicker.gif

参考URL

RailsとBootstrap4 でカレンダー形式の日付入力フォームを実装する
Tempus Dominus
Moment.js

12
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?