Help us understand the problem. What is going on with this article?

railsでflashを使ってサクセス・エラーメッセージを表示する

More than 1 year has passed since last update.

仕様書

  • flashを用いて登録が成功したかを次の画面で表示する

流れ

  • controller.rbに@post.saveができたら成功のメッセージ、失敗したら失敗のメッセージをflash[:notice]に入れるようにする
  • viewにもしflash[:notice]があったらそれを表示するようにする
  • 失敗したら投稿フォームに戻り、投稿フォームに前入力してた値を初期値として出す。

controllerにsaveがされたかでflash[:notice]を振り分けて表示するようにする

posts_controller.rb
  def create
    @post = Post.new(content: params[:content])
    if @post.save
      flash[:notice] = "投稿を作成しました"
      redirect_to("/posts/index")
    else
      render("posts/new")
    end
  end

viewにメッセージの表示

application.html.erb
    <% if flash[:notice] %>
      <div class="flash">
        <%= flash[:notice] %>
      </div>
    <% end %>

もしflash[:notice]があった場合のみ発動。

もし失敗した場合、投稿ページに戻る。

new.html.rb
<% @post.errors.full_messages.each do |message| %>
 <div class="form-error">
  <%= message %>
 </div>
<% end %>
<textarea name="content"><%= @post.content %></textarea>
<input type="submit" value="投稿">
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away