前提・実現したいこと
DBに保存したい
発生している問題・エラーメッセージ
1ページでデータの一覧と、入力フォームが表示されるようにしています。
index.etml.erb上では保存を行えます。
空データを保存した場合にエラーが出力される用のnew.etml.erb上でデータを入力すると保存が行えません。
該当のソースコード
books_controller.rb
def new @books=Book.new end def create @book=Book.new(title: params[:title],body: params[:body]) if @book.save flash[:notice]="Book was successfully created." redirect_to book_path(@book.id) else @books=Book.all render :new end end def index @books=Book.all end
index.html.erb
<html> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="books.scss"> <title>index</title> </head> <body> <% if flash[:notice] %> <div class="flash-message"><p> <%= notice%> </p></div> <% end %> <h1>Books</h1> <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),class:"link" %></td> <td><%= link_to "Edit",edit_book_path(book.id),class:"link" %></td> <td><%= link_to "Destroy",destroy_list_path(@books.ids), method: :delete, data: {confirm: "削除しますか?"},class:"link" %></td> </tr> <% end %> </tbody> </table> <h2>New book</h2> <%= form_with model: @book, url:books_path, method: :post do |f| %> <div class="field"> <%= f.label :title %> <%= f.text_field :title %> </div> <div class="field"> <%= f.label :body %> <%= f.text_area :body %> </div> <div class="actions"> <%= f.submit "Create Book" %> </div> <% end %> </body> </html>
new.html.erb
<html> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="books.scss"> <title>new</title> </head> <body> <% if flash[:notice] %> <div class="flash-message"><p> <%= notice%> </p></div> <% end %> <h1>Books</h1> <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),class:"link"%></td> <td><%= link_to "Edit",edit_book_path(book.id),class:"link" %></td> <td><%= link_to 'Destroy',book_path(book.id), method: :delete,class:"link" %></td> </tr> <% end %> </tbody> </table> <h2>New book</h2> <div class="error-message"> <% if @book.errors.any? %> <div class="error-title"><%= @book.errors.count %> errors prohibited this book from being saved:</div> <ul> <div class="error-list"> <% @book.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </div> </ul> <% end %> </div> <%= form_with model: @book, url:books_path, method: :post do |f| %> <div class="field"> <%= f.label :title %> <%= f.text_field :title %> </div> <div class="field"> <%= f.label :body %> <%= f.text_area :body %> </div> <div class="actions"> <%= f.submit "Create Book" %> </div> <% end %> </body> </html>
どなたか解決お願いします。
まだ回答がついていません
会員登録して回答してみよう