フラッシュメッセージ
Railsで用意されているflashオブジェクトはハッシュ形式で、メッセージタイプがキー、メッセージが値である。ビューでは以下の形で表示できる。
<% flash.each do |message_type, message| %> <!-- alertなどはbootstrapのクラス名 --> <div class="alert alert-<%= message_type %>"><%= message %></div> <% end %>
add_flash_type
add_flash_typesでBootstrapに用意されているメッセージタイプを指定すると、リダイレクト時に表示させるときの記述を簡潔にできる。
application_controller.rb
# Bootstrapに用意されているスタイルのフラッシュを定義 add_flash_types :success, :info, :warning, :danger
articles_controller.rb
def create if @article.save redirect_back_or_to root_path, success: '成功です' # リダイレクト時 else flash.now[:danger] = '失敗です' # 一般的な書き方 render :new end end