以下の点で悩んでおります。(当方rails初心者です)
読んだ本の感想を投稿するサイトを練習中
バリデーションを使い、投稿時の未入力のエラーメッセージを作成中に起こっているエラーを解決したい。
実現したいこと
バリデーション機能を動作するようにする
発生している問題・エラーメッセージ
NoMethodError in Books#create
Showing /home/ec2-user/environment/bookers/app/views/books/index.html.erb where line #11 raised:
undefined method `each' for nil:NilClass
Extracted source (around line #11):
該当のソースコード
【HTML】
<h2>Books</h2> <table> <thead> <tr> <th>Title</th> <th>Body</th> <th colspan="3"></th> </tr> </thead> <tbody> <% @books.each do |book| %> <tr> <td><%= book.title %></td> <td><%= book.body %></td> <td><%= link_to "Show", book_path(book.id) %></td> <td><%= link_to "Edit", edit_book_path(book) %></td> <td><%= link_to "Destroy", destroy_book_path(book.id), method: :delete, "data-confirm" => "Are you sure?" %></td> </tr> <% end %> </tbody> </table> <h3>New book</h3> <% if @book.errors.any? %> <%= @book.errors.count %>件のエラーが発生しました <ul> <% @book.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> <% end %> <!-- form_with部分 --> <%= form_with model: @book, url: '/books', method: :post do |f| %> <p>Title</p> <%= f.text_field :title %> <p>Body</p> <%= f.text_area :body %><br><%= f.submit 'Create Book' %>
<% end %>
【コントローラ】
class BooksController < ApplicationController
def create
@book = Book.new(book_params)
if @book.save
flash[:notice] = "Book was successfully created."
redirect_to book_path(@book.id)
else
render :index
end
end
def index
@book = Book.new
@books = Book.all
end
def show
@book = Book.find(params[:id])
end
def edit
@book = Book.find(params[:id])
end
def update
book = Book.find(params[:id])
book.update(book_params)
flash[:notice] = "Book was successfully updated."
redirect_to book_path(book.id)
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
【RUBY】
class Book < ApplicationRecord
validates :title, presence: true
validates :body, presence: true
end
試したこと
ネットでの検索
コントローラの変更
補足情報(FW/ツールのバージョンなど)
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。