1
3

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 3 years have passed since last update.

【Rails】date_selectを使ってみた

Last updated at Posted at 2020-04-14

#学習メモです
タスクに期限を設定したくてカレンダーだと面倒なので日付選択が簡単なdate_selectを使ってみた。
#型
html.slim


    = f.date_select(:カラム名,
                    use_month_numbers: true,
                    start_year:        Date型で最初の日付,
                    end_year:          Date型で終了の日付(interger型なので+5などでつければOK,
                    default:           何も入力しなかった場合の値,
                    date_separator:    '区切りかた')

#実際に書いたコード


    = f.date_select(:start_at,
                    use_month_numbers: true,
                    start_year:        Date.today.year,
                    end_year:          Date.today.year + 5,
                    default:           Date.today,
                    date_separator:    '/')

今paramsになにが来ているのかbinding.pryで見てみる

 <ActionController::Parameters {"utf8"=>"✓", "authenticity_token"=>"e12hjdLpjd/M5iuOGCkPaK5gZE6oR5US4HLybq1zKMNP178svzeGhjg6y2a3Fu6XnrlFuIKnkKtJgvIFqs6rkQ==", "task"=>{"name"=>"", "description"=>"", "start_at(1i)"=>"2020", "start_at(2i)"=>"2", "start_at(3i)"=>"30", "priority"=>"low", "completed"=>"doing"}, "commit"=>"Create Task", "controller"=>"tasks", "action"=>"create"} permitted: false>

ちゃんと"start_at(1i)"=>"2020", "start_at(2i)"=>"2", "start_at(3i)"=>"30"がきていたのでこれをsaveする。

controllerのcreateアクションで


time = Date.new(params[:task]["start_at(1i)"].to_i,params[:task]["start_at(2i)"].to_i,params[:task]["start_at(3i)"].to_i)
if time.save
  redirect_to :index
else
  render :new
end

これはparamsに入っているhashから要素を取り出しDateクラスの引数に入力してインスタンスを生成している。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?