Rails 4:收到以下错误:表单中的第一个参数不能包含nil或为空

我在我的项目中收到以下错误:表单中的第一个参数不能包含nil或为空。 我正在尝试为我的代码创建一个编辑页面。 Rails相当新,并试图学习没有脚手架。

控制器:

class BooksController < ApplicationController def new @book = Book.new @authors = Author.all end def edit @book = Book.find(params[:id]) end def show #Notice how the @books is plural here. @books = Book.all @authors = Author.all #@books = Book.where(id: params[:id]) end #Create method will save new entries def create @book = Book.new(book_params) @authors = Author.all if @book.save flash[:success] = "Book Added to Databse!" redirect_to @book else render 'new' end end private #Note that this method will go up into the create method above. def book_params params.require(:book).permit(:title, :pub_date, :publisher, :author_id) end end 

型号页面:(适用于本书)

 class Book < ActiveRecord::Base validates :title, :pub_date, :publisher, presence: true validates :title, uniqueness: true belongs_to :author end 

型号页:(作者)

 class Author < ActiveRecord::Base validates :name, presence: true validates :name, uniqueness: true has_many :books end 

编辑页面:

 

Update a book entry

**ERROR SEEMS TO BE RIGHT HERE!!!**

'Please select an author'}, class: "form-control") %>

渲染表单页面(_form.html.erb)

   

prohibited this entry from being saved:

显示页面:

  

Showing Book Titles:


这是我的日志告诉我出了什么问题:

 Started GET "/edit" for ::1 at 2015-08-14 16:49:17 -0400 Processing by BooksController#edit as HTML Rendered books/edit.html.erb within layouts/application (2.2ms) Completed 500 Internal Server Error in 9ms (ActiveRecord: 0.0ms) ActionView::Template::Error (First argument in form cannot contain nil or be empty): 3: 
4:
5: 6: 7: 8: 9:
app/views/books/edit.html.erb:6:in `_app_views_books_edit_html_erb___525891009649529081_70260522100960'

我会说我已从我的数据库中删除了前14本书,因此第一本书从ID 14开始。不确定这是否重要。

最后,我尝试在编辑方法中将所有这些不同的实例变量添加到我的控制器:

  #@book = Book.where(id: params[:id]) #@book = Book.find_by_id(params[:id]) #@book = Book.all #@book = Book.find_by_id(params[:id]) #book = Book.new(book_params) #When I use the two below lines, there are no error pages but create a new entry. #@book = Book.new #@authors = Author.all 

任何帮助将不胜感激! 感谢您的时间!!!

此错误意味着form_for的第一个参数是nil值(在本例中为@book )。 我见过这种情况的大部分时间,通常都是错误的控制器操作,但这看起来并非如此。 据我所知,这是两件事之一:

  1. 您正在尝试编辑不存在的图书。 做一个.nil? 在决定呈现表单之前检查它,并呈现错误消息(或重定向)。

  2. 您的路线已损坏, edit操作未呈现edit视图。 这很可能不是这种情况。

编辑:

使用show for template更新后,这看起来像是你的问题:

<%= link_to "Edit", edit_path, class: "btn btn-primary" %>

我发现这有两个问题(虽然我需要查看rake routes的输出来validation)。 首先,你需要将一个参数传递给编辑路径(没有它们,你的参数来自哪里?)。 其次,默认路由是edit_book_path

试试这个:

<%= link_to "Edit", edit_book_path(book), class: "btn btn-primary" %>

假设书ID 14在您的数据库中,您应该能够导航到localhost:3000/books/14/edit如果您使用resources :books创建它resources :books ( 这里的文档)。 如果这不起作用,则无法正确定义路由,或者数据库中不存在ID为14的书。

在您的节目视图中,将link_to行更改为:

 <%= link_to 'Edit', edit_book_path(book), class: "btn btn-primary" %> 

所以有两个变化:

  1. 同样,假设book是Restful资源,当您运行rake_routes ,您应该看到要编辑的路径是edit_book_path
  2. 您需要使用路径传递book实例,以便Rails知道您要编辑哪个对象。

我在这里找到了正确的语法。

希望这可以帮助。