発生している問題・エラーメッセージ
該当のソースコード
app/models/book.rb
Ruby
1class Book < ApplicationRecord 2 validates :title, presence: true 3 validates :body, presence: true 4end
app/config/routes.rb
Ruby
1Rails.application.routes.draw do 2 # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html 3 root to: 'homes#top' 4 get 'top' => 'homes#top' 5 get 'todolists/new' 6 post 'todolists' => 'todolists#create' 7 get 'todolists' => 'todolists#index' 8 get 'todolists/:id' => 'todolists#show',as:'todolist' 9 get 'todolists/:id/edit' => 'todolists#edit',as:'edit_todolist' 10 patch 'todolists/:id' => 'todolists#update',as:'update_todolist' 11 delete 'todolists/:id' => 'todolists#destroy',as:'destroy_todolist' 12end
app/controllers/todolists_controller.rb
Ruby
1class TodolistsController < ApplicationController 2 3 def new 4 @book = Book.new 5 end 6 7 def create 8 book = Book.new(book_params) 9 if book.save 10 redirect_to todolist_path(book) 11 flash[:notice] = "Book was successfully created." 12 else 13 render 'new' 14 end 15 end 16 17 def index 18 @books = Book.all 19 end 20 21 def show 22 @book = Book.find(params[:id]) 23 end 24 25 def edit 26 @book = Book.find(params[:id]) 27 end 28 29 def update 30 book = Book.find(params[:id]) 31 if book.update(book_params) 32 redirect_to todolist_path(book) 33 flash[:notice] = "Book was successfully updated." 34 else 35 render 'edit' 36 end 37 38 def destroy 39 @book = Book.find(params[:id]) 40 @book.destroy 41 redirect_to todolists_path 42 end 43 44 private 45 def book_params 46 params.require(:book).permit(:title,:body) 47 end 48end
app/views/todolists/new.html.erb
Ruby
1<h2>New Book</h2> 2 3<%= form_for(@book,url:'/todolists') do |f| %> 4 <% if @book.errors.any? %> 5 <div> 6 <h2><%= @book.errors.count %>件のエラーがあります。</h2> 7 <ul> 8 <% @book.errors.full_messages.each do |msg| %> 9 <li><%= msg %></li> 10 <% end %> 11 </ul> 12 </div> 13 <% end %> 14 <h6>Title</h6> 15 <%= f.text_field :title %> 16 17 <h6>Body</h6> 18 <%= f.text_area :body %> 19 20 <p><%= f.submit 'Create Book' %></p> 21 22<% end %>
補足情報(FW/ツールのバージョンなど)
PC : MacBook Air 2017
OS : macOS Catalina
Editer : Sublime Text3
Vagrant : 2.2.7
VirtualBox : 6.1.2
ここにより詳細な情報を記載してください。
前提・実現したいこと
Ruby on Railsで、「本の感想を投稿できるサイト」という名目の簡易投稿サイトを作成中です。
新規投稿時、タイトル又は本文が空白であった場合にエラーメッセージを表示させようとしたところ、上記のエラーが発生してしまいました。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/02/24 08:16