1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails】flashメッセージ

Last updated at Posted at 2025-03-27

flashメッセージとは

アクション実行後に簡単なメッセージを表示させるRailsの機能。

コントローラーに記述

flashuの書き方

flash[:キー名]="表示したいメッセージ"

これはコントローラに記述する。
キー名は好きな名前をつけることができる。

# 例)
flash[:notice] = "お知らせです"
flash[:alert] = "警告です"

フラッシュメッセージを表示させる箇所にはviewファイルに以下のように記載する。

<%= flash[:キー名] %>

noticeとalertオプション

キーには好きな名前をつけることができるが、noticealertは、<%= flash[:キー名] %>と書く必要がない。viewファイルは以下のようにflashを省略してかける。

<%= notice %>
<%= alert %>

他のキー名でもまとめて書くことができるその場合は下記のようになる。

redirect_to ("パス"), flash{キー名: '表示するメッセージ' }

redirect_toでnoticeとalertを使う時はまとめて書くことができる

redirect_to ("パス"), notice: '表示するメッセージ' 
class TasksController < ApplicationController
  def index
    @tasks = Task.order(created_at: :desc) # order(created_at: :desc)は作成順に降順に並び替え、タスクを取得
    @tasks = Task.new # 新しいTaskオブジェクトを作成
  end

  def create
    @task =Task.new(task_params) # フォームの入力値を使って新しいTaskオブジェクトを作成
    if @task.save # @taskをデータベースに保存したとき
      redirect_to root_path, notice: "タスクを作成しました"
      # noticeはflashメッセージの成功通知 root_pathはトップページへリダイレクト
    
    end
  
end

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?