困っていること、実現したいこと
編集画面を表示したいのですが以下のように、パラメータが入っていないとエラーがでます。
class ArticlesController < ApplicationController # only とかかれたメソッドのみメソッド実行直後に set_article が実行される before_action :set_article, only: [:edit, :update, :show, :destroy] def index @articles = Article.all end def new @article = Article.new end def edit if @article.update(article_params) flash[:notice] = "記事の編集に成功しました" # 受け取った@articleをshow.htmlで表示する redirect_to article_path(@article) else # edit.htmファイルを表示する render 'edit' end end def create # 記事の作成を行う @article = Article.new(article_params) # 保存が成功すれば、 if @article.save flash[:notice] = "記事の作成に成功しました" # 生成した記事を view に飛ばす redirect_to article_path(@article) else render 'new' end end def update if @article.update(article_params) flash[:notice] = "記事の更新に成功しました" redirect_to article_path(@article) else render 'edit' end end def show end def destroy @article.destroy flash[:notice] = "記事の削除に成功しました" # 特定の記事を削除した後、一覧に戻る redirect_to article_path end private # 特定のarticleを検索する # よく出るメソッドなのでbefore_actionで実行した def set_article @article = Article.find(params[:id]) end # articleを作成するときtitleとdescriptionのみ許可する。 def article_params params.require(:article).permit(:title, :description) end end
_form.html.erb
<% if @article.errors.any? %> <h2>次のエラーにより、記事が作成できませんでした。</h2> <ul> <% @article.errors.full_messages.each do |msg| %> <li><%= msg %></li> <% end %> </ul> <% end %> <%= form_for @article do |f| %> <p> <%= f.label :タイトル %> <%= f.text_field :title %> </p> <p> <%= f.label :説明欄 %> <%= f.text_area :description %> </p> <p> <%= f.submit %> </p> <% end %> <%= link_to "記事一覧に戻る", article![イメージ説明](9bf92d2038ebfd6883b04e84e08df721.png) %>
edit.html.erb
<h1>作成済みの記事を編集する</h1> <%= render 'form' %>
FW:Rails 5.0.7.2
開発言語:Ruby 2.6.3
デバッグの丸投げになってます。
https://teratail.com/help/avoid-asking
「エラーがでます」じゃなく、どこまで自分で調査してどこがわからないのか書きましょう。
回答1件
あなたの回答
tips
プレビュー