4
6

More than 3 years have passed since last update.

[Rails]サクセスメッセージとエラーメッセージの出し方

Last updated at Posted at 2020-10-30

はじめに

twitterのようなアプリで投稿する際のサクセスメッセージやエラーメッセージの出し方についてまとめてみました。僕自身初めてこの機能をつける時手間だったので同じような悩みを持つ人のために投稿します。

バージョン

ruby 2.5.7
Rails 5.2.4.3

サクセスメッセージの出し方

コントローラー
   flash[:notice] = "successfully" 

コントローラーのcreateアクションとupdateアクションのなかに↑の記述をします。

ビュー
   <% if flash[:notice] %>
     <p id="notice">
       <%= flash[:notice] %>
     </p>
   <% end %>

サクセスメッセージを出したいビューのページに↑の記述をします。
これで、投稿できた際に"successfully"という文字が出てくると思います。

エラーメッセージの出し方

コントローラー
def create
      @book = Book.new(book_params)
      @book.user_id = current_user.id
      if @book.save
        flash[:notice] = "successfully"
        redirect_to book_path(@book)
   #ここから
      else
        @books = Book.all
        render 'index'
   #ここまで
      end
    end

よくエラー起きるのがここです。saveができなかったときの動作を記述しましょう

ビュー
<% if @book.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@book.errors.count, "error") %> prohibited this book from being saved:</h2>
      <ul>
        <% @book.errors.full_messages.each do |message| %>
          <li><%= message %></li>
        <% end %>
      </ul>
    </div>
<% end %>

エラーメッセージを出したいビューとコントローラーに↑を記述します。
そうすれば、バリデーションに引っかかって投稿できない時にエラーメッセージが出てくるでしょう。

最後に

詳しく知りたい方はこちらも参考にしてみてください。

4
6
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
4
6