学習1週間の初学者です。
前提・実現したいこと
バリデーションエラーメッセージを表示させたいのですが、
エラーが出てしまいます。
どのようにすればいいのでしょうか。
発生している問題・エラーメッセージ
NoMethodError in Books#update Showing /home/ec2-user/environment/bookers/app/views/books/edit.html.erb where line #3 raised: undefined method `errors' for nil:NilClass Extracted source (around line #3): 1 2 3 4 5 6 <%= form_with model:@book, local:true do |f| %> <% @book.errors.full_messages.each do |message| %> <%= message %> <% end %>
###コントローラー
class BooksController < ApplicationController def index @books = Book.all @book = Book.new end def new @book = Book.new end def create @book = Book.new(book_params) if @book.save flash[:success] = 'successfully' redirect_to book_path(@book.id) else @books = Book.all render 'index' end end def show @book = Book.find(params[:id]) end def edit @book = Book.find(params[:id]) end def update book = Book.find(params[:id]) if book.update(book_params) flash[:success] = 'successfully' redirect_to book_path(book.id) else @books = Book.all render 'edit' end end def destroy book = Book.find(params[:id]) book.destroy redirect_to '/books' end private def book_params params.require(:book).permit(:title, :body) end end
###routes
Rails.application.routes.draw do root to: 'books#top' get 'top' => 'books#top' get 'book/new' get 'books' => 'books#index' post 'books' => 'books#create' get 'books/:id' => 'books#show', as: 'book' get 'book/:id', to: 'books#show' get 'books/:id/edit' => 'books#edit', as: 'edit_book' patch 'books/:id' => 'books#update', as: 'update_book' delete 'books/:id' => 'books#destroy', as: 'destroy_book' end
###edit.html.erb
<%= form_with model:@book, local:true do |f| %> <% @book.errors.full_messages.each do |message| %> <%= message %> <% end %> <h4>タイトル</h4> <%= f.text_field :title %> <h4>本文</h4> <%= f.text_area :body %> <%= f.submit 'Update Book' %> <% end %> <%= link_to "show", book_path %> <%= link_to "Back", '/books' %>
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/11/16 07:51
2020/11/16 11:53
2020/11/16 12:47
2020/11/16 13:05
2020/11/17 02:22