LoginSignup
3
2

More than 3 years have passed since last update.

[Rails]フラッシュメッセージを一定時間で消す方法

Last updated at Posted at 2020-12-16

開発環境

・Ruby: 2.5.7
・Rails: 5.2.4
・Vagrant: 2.2.7
・VirtualBox: 6.1
・OS: macOS Catalina

実装

Gemfile
gem 'jquery-rails'
ターミナル
bundle install
controller

  def create
    @book = Book.new(book_params)
    @book.user_id = current_user.id
    if @book.save
      redirect_to book_path(@book)
      flash[:notice] = "本が投稿されました"
    else
      @books = Book.all
      flash.now[:alart_flash] = "本の投稿に失敗しました"
      render 'index'
    end
  end

本が投稿された時にはnotice、失敗した際にはalart_flashと名付けて判別。ここの名前は自分で変えてもOK!
flash[:]にすると、次のアクションまで表示させる。
flash.now[:]にすると、次のアクションに移行した時点で消える仕組みになっているので
renderは指定したviewsを呼び出すだけなので、アクションではないから気をつける。
redirect_toは次のアクションになるので、flash.nowだと表示がされないので注意が必要

フラッシュメッセージ装飾

application.scss
.flash{
  width: 100%;
  height: 30px;
  font-size: 18px;
  text-align: center;
  padding: 0;
  z-index: 1;
}

.notice{
  background-color: #65A2FF;
}

.alart_flash{
  color: #FFFFFF;
  background-color: #FF0000;
}

一定時間でフラッシュメッセージを消す。

application.js
// フラッシュメッセージ
$(function(){
  $('.flash').fadeOut(4000);  //4秒かけて消えていく
});

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