LoginSignup
24
24

More than 5 years have passed since last update.

RailsでモデルのDateTIme型プロパティをformで良い感じに表示してみる

Last updated at Posted at 2016-01-15

Datetime型のプロパティについて、フォームで良い感じに表示する方法に手間取ったので備忘録。

見た目はこんな感じ。
スクリーンショット 2016-01-15 19.08.22.png

実行環境
ruby 2.2.3p173
Rails 4.2.5

form.html.erb
<%# 例えば article オブジェクトに start_at(Datetime型) というプロパティを持っている場合 %>

<%= form_for @article, url: hogehoge_path do |f| %>
  <%= f.label :start_at, '掲載開始日' %>
  <%= raw sprintf(
    f.datetime_select(
      :start_at,# プロパティ名
      {
        start_year:     Time.zone.now.prev_year.year,# 選択可能な開始年
        end_year:       Time.zone.now.next_year.year,# 選択可能な終了年
        default:        Time.zone.now,# デフォルトの年
        use_two_digit_numbers: true,# 月日を2桁の値で表示
        date_separator: '%s',# 年, 月
        datetime_separator: '%s',# 日
        time_separator: '%s'# 時
      },# オプション
      { class: 'date-select' }# htmlオプションを指定する場合は別で指定
    ),
    '年 ', '月 ', '日 ', '時 ') + '分'# 分 は最後につけ加えられる
  %>
<% end %>

separatorの情報って意外と少なくて苦労しました…。

24
24
3

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
24
24