バリデーション
バリデーションとは、不正なデータがデータベースに保存されないようにする仕組み。
バリデーションに引っかかった場合はfalseを返す
投稿のバリデーション
投稿が空白、140文字以上の場合はsaveできないようにする。
models/post.rb
validates :content,{presence: true,length: {maximum: 140}}
これにより遷移ページを変える
posts_controller.rb
def update
@post = Post.find_by(id: params[:id])
@post.content = params[:content]
if @post.save
flash[:notice] = "投稿を編集しました"
redirect_to("/posts/index")
else
redirect_to("posts/edit")
end
end
ただこのままだと、バリデーションに引っかかってeditに移った時に投稿のデータがなくなってしまうため、renderメソッドを用いる。
renderメソッド
renderメソッドを用いることで、別のアクションを経由せずに直接ビューを表示することができる。
renderを使う場合は、そのアクション内で定義した@変数をビューで用いることができる。
posts_controller.rb
def update
@post = Post.find_by(id: params[:id])
@post.content = params[:content]
if @post.save
flash[:notice] = "投稿を編集しました"
redirect_to("/posts/index")
else
render("posts/edit")
end
end
この場合はeditアクションを経由せずにedit.html.erbを表示できる。
エラーメッセージを表示する
saveメソッドに失敗した時、railsでは自動的にエラーメッセージが@post.errors.full_messagesの中に作られている。
これを編集ページに記述しておく。
edit.html.erb
<% @post.errors.full_messages.each |message| do %>
<%= message %>
<% end %>
サクセスメッセージを表示する
フラッシュ
ページ上に一度だけ表示されるメッセージのこと。
保存に成功した時の、サクセスメッセージとしてflash定数を定義しておく。
posts_controller.rb
def update
@post = Post.find_by(id: params[:id])
@post.content = params[:content]
if @post.save
#保存に成功した場合、フラッシュメッセージを作る
flash[:notice] = "投稿を編集しました"
redirect_to("/posts/index")
else
render("posts/edit")
end
end
またflashは色々なところで使うので、共通のレイアウトとする。
application.html.erb
<% if flash[:notice] %>
<div class="flash">
<%= flash[:notice] %>
</div>
<% end %>
続き
https://qiita.com/jonnyjonnyj1397/items/833b0816da6ed7be085c