bootstrap3-datetimepickerをとりあえず入れてみた
bootstrap3-datetimepickerが必要になった
日付と日時を入れるのに使用したのがbootstrap3-datetimepicker。
今回はメモするのが面倒なので、ひたすらにコードを貼っていく。
# Gemfile gem 'momentjs-rails' gem 'bootstrap3-datetimepicker-rails'
で、sudo bundle installして。
// application.js //= require moment //= require moment/ja //= require bootstrap-datetimepicker var data = {'data-date-format': 'YYYY-MM-DD hh:mm' }; $(function(){ $('.datepicker').attr(data); $('.datepicker').datetimepicker({ format: 'YYYY-MM-DD hh:mm', locale: 'ja', dayViewHeaderFormat: 'YYYY年 MM月' }); });
ここでカレンダーの見た目やクリックした際のテキスト出力を変更する。
//= require moment //= require bootstrap-datetimepicker
ここは最低限必要。
//= require moment/ja
これは日本語化するのに必要。下のものと合わせて使う。
locale: 'ja', dayViewHeaderFormat: 'YYYY年 MM月'
以下はひたすらコピペ。
/* application.css */ *= require bootstrap-datetimepicker
# articles_controller.rb def create @article = Article.new(article_params) @article.user_id = current_user.id respond_to do |format| if @article.save format.html { redirect_to @article, notice: 'Article was successfully created.' } format.json { render :show, status: :created, location: @article } else format.html { render :new } format.json { render json: @article.errors, status: :unprocessable_entity } end end end # PATCH/PUT /articles/1 # PATCH/PUT /articles/1.json def update respond_to do |format| if @article.update(article_params) format.html { redirect_to @article, notice: 'Article was successfully updated.' } format.json { render :show, status: :ok, location: @article } else format.html { render :edit } format.json { render json: @article.errors, status: :unprocessable_entity } end end end private def article_params params.require(:article).permit(:title, :meta_description, :content, :published_at) end
publised_atに追加したいからそれを許可する。
/ _form.html.slim = form_for @article do |f| .input-group.date.datepicker = f.label :投稿時間 = f.text_field :published_at, class: 'form-control' span.input-group-addon
でもうまくいかなくて
こうすると、ページ遷移したときにうまくいかないんですよね、、
よくわからない。
今回解消したのは{:method => :get }を追加する方法。
link_to '編集', edit_article_path(@article), {:method => :get }
下のを追加するという方法もあったのだが、なぜか機能しなかったので諦めた。
$(document).on 'ready page:load', ->
参考 ↓
まとめ(個人的なやつ)
機能を実装するときは複数のサイトを見比べることで、
- より良い構成案が浮かぶ
- どのコードがどの役割をしているか予想がつく
などのメリットがあるんですねえ。
参考
[Rails]日付と時間の入力フォームにDateTimePickerを使う(bootstrap3-datetimepicker-rails) – hello-world.jp.net
rails で bootstrap3-datetimepicker を使ってみた - spring of life