LoginSignup
1
2

More than 5 years have passed since last update.

ラベルで時刻を選択する メモ

Posted at

時刻を定形リストから選択できるようにしたい

概要

たとえば時間割など、決まった時刻セットを選択してもらいたい場合は、time_select メソッドは不向き。
time_select で実現できなければ、ただのselect でやってみよう。

time_select メソッド

時刻選択

通常ならば、time_select メソッドで必要順分な機能があるとおもう。
1分刻みじゃなくって15分刻みにしたいなら、minuite_step: 15でできるし、秒数を選択肢に含めることもできる。
(詳しくはリファレンスを参照のこと。)

文字列で選択したい

文字列で選択

time_select のように時刻で選択するのではなく、文字列で選択したい場合、select メソッドを利用する。

ベタ書き:

app/views/schedules/_form.html.erb
<%= f.select :time, [['Period 1', '09:30']['Period 2', '10:30']] %>

ヘルパーメソッドにリストを移動、Viewで使う:

app/helpers/application_helper.rb

  def time_list
    [
      ['Period 1', '09:30'],
      ['Period 2', '10:30'],
      ['Period 2', '11:30'],
      ['Period 3', '13:45'],
      ['Period 4', '14:45'],
      ['Period 5', '15:45'],
      ['Period 6', '16:45'],
      ['Period 7', '17:45']
    ]

  end


app/views/chedules/_form.html.erb
<%= f.select :time, time_list %>

リンク

Ruby on Rails Documentation
* ActionView::Helpers::DateHelper
* ActionView::Helpers::FormOptionsHelper

1
2
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
1
2