我正在尝试按照本教程。它已在Rails的早期版本中编写,我正在使用Rails 4.在“为新方法创建视图文件”一节中,我更新了给定的代码示例以使用当前的Rails但我收到以下错误:
ActiveRecord::RecordInvalid in BookController#create
Validation failed: Title can't be blank, Price Error Message
Extracted source (around line #14):
12 def create
13 @book = Book.new(book_params)
14 if @book.save!
15 redirect_to :action => 'list'
16 else
17 @subjects = Subject.all
Rails.root: C:/Ruby193/mylibrary
Application Trace | Framework Trace | Full Trace
app/controllers/book_controller.rb:14:in `create'
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"Xla1xJlMqCx96ZITbI6JHOvoNIoAHc5ItcZgcMzs0/Y=",
"title"=>"asd",
"price"=>"asd",
"book"=>{"subject_id"=>"1"},
"description"=>"asd",
"commit"=>"Create",
"method"=>"post"}
这是我的路由文件:
Rails.application.routes.draw do
get 'book/list' => 'book#list'
get 'book/new' => 'book#new'
post 'book/create' => 'book#create'
end
这是我的控制器类:
class BookController < ApplicationController
def list
@books = Book.all
end
def show
@book = Book.find(params[:id])
end
def new
@book = Book.new
@subjects = Subject.all
end
def create
@book = Book.new(book_params)
if @book.save!
redirect_to :action => 'list'
else
@subjects = Subject.all
render :action => 'new'
end
end
def edit
@book = Book.find(params[:id])
@subjects = Subject.all
end
def update
@book = Book.find(params[:id])
if @book.update_attributes(book_params)
redirect_to :action => 'show', :id => @book
else
@subjects = Subject.all
render :action => 'edit'
end
end
def delete
Book.find(params[:id]).destroy
redirect_to :action => 'list'
end
private
def book_params
params.require(:book).permit(:title, :price, :description)
end
end
这是view- new.html
<h1>Add new book</h1>
<%= form_tag(controller: "book", action: "create", method: "post") do %>
<%= label_tag(:title, "Title") %>
<%= text_field_tag(:title) %><br>
<%= label_tag(:price, "Price") %>
<%= text_field_tag(:price) %><br>
<%= label_tag(:q, "Subject") %>
<%= collection_select(:book,:subject_id,@subjects,:id,:name) %><br>a
<%= label_tag(:description, "Description") %><br>
<%= text_area_tag(:description) %><br>
<%= submit_tag( "Create") %>
<%end %>
<%= link_to 'Back', {:action => 'list'} %>
我该怎么办?提前谢谢
答案 0 :(得分:0)
您需要更改表单,以便将:title属性正确放置在参数中的book键下方。还有其他助手可以让你这样做:
尝试更改以下行:
label_tag( :title )
text_field_tag(:title)
到
label( :book, :title )
text_field(:book, :title )
答案 1 :(得分:-1)
在您的创建方法中,使用save
而不是save!
save!
会以您看到的方式抛出验证错误,save
会向@book
对象添加错误消息,以便用户可以在表单中修复它们。
有关详细信息,请参阅the documentation。
def create
@book = Book.new(book_params)
if @book.save
redirect_to :action => 'list'
else
@subjects = Subject.all
render :action => 'new'
end
end