【发布时间】:2016-08-31 15:29:50
【问题描述】:
我找不到为什么属性:description 返回nil 的错误。
来自rails console:
@book = Book.first
# Book Load (0.7ms) SELECT "books".* FROM "books" ORDER BY "books"."id" ASC LIMIT 1
#=> #<Book id: 1, title: "A Game of Thrones", description: nil, author: "George R. R. Martin ", created_at: "2016-09-01 13:27:09", updated_at: "2016-09-01 13:27:09">
books_controller.rb
class BooksController < ApplicationController
before_action :find_book, only: [:show, :edit, :update, :destroy]
def index
@books = Book.all.order("created_at DESC")
end
def show
@book = Book.find(params[:id])
end
def new
@book = Book.new
end
def create
@book = Book.new(book_params)
if @book.save
redirect_to root_path
else
render 'new'
end
end
private
def book_params
params.require(:book).permit(:description, :title, :author)
end
def find_book
@book = Book.find(params[:id])
end
end
_form.html.erb
<%= f.input :title, label: "Book Title" %>
<%= f.input :description %>
<%= f.input :author %>
<%= f.button :submit %>
'show.html.erb'
<h2><%= @book.title %></h2>
<h3><%= @book.author %></h3>
<h2><%= @book.description %></h2>
路由.rb
'Rails.application.routes.draw 做 资源:书籍 根'书#索引' 结束'
【问题讨论】:
-
我想您已经尝试通过您的
BooksController从表单创建一本书。你能显示已经传递给你的控制器的参数吗?您可以在应用程序的日志文件中找到它们。 -
尝试创建一个新记录并查看没有描述的记录。从控制台
-
您使用的是哪个版本的 Rails?您的 Gemfile 中是否声明了“protected_attributes”gem?你的
Bookmodel 中有“attr_accessible”吗? -
看起来没有什么问题。既然您查询了
Book.first,那可能一开始就没有描述?你能检查一下数据库中是否有书籍有描述吗? -
嗨,安娜,欢迎来到 SO。我标记了您的问题,因为我们可能需要更多信息 (stackoverflow.com/help/how-to-ask)。也许只是你的第一本书错了。检查
Book.last以查看描述是否已保存。
标签: ruby-on-rails ruby null return