0

嘿,我还有另一个问题;)

当我尝试在我的应用程序中创建一本新书时,它总是说

undefined method "model_name" for NilClass:Class

我发现它必须是 Form_for 函数中未初始化的参数......这是我的代码:

NoMethodError in Books#new

Showing /app/views/books/_form.html.erb where line #1 raised:

   undefined method `model_name' for NilClass:Class
   Extracted source (around line #1):

   1: <%= form_for(@book) do |f| %>
   2:   <% if @book.errors.any? %>
   3:     <div id="error_explanation">
   4:       <h2><%= pluralize(@book.errors.count, "error") %> prohibited this book from being saved:</h2>

控制器:

   #GET /books/new
   #GET /books/new.json
   def new
     @users = User.find(:all)
     @book = Book.new
     1.times{ @book.chapters.build }
     @book.users = [current_user]
     respond_to do |format|
       format.html #new.html.erb
       format.json { render json: @book }
     end
    end

我不知道为什么它应该未初始化,在我改变书籍和用户之间的一些关系之前它工作正常,但我不应该是失败还是?

编辑:

app/views/books/new.html.erb :

    <h1>New book</h1>

    <%= render 'form' %>

    <%= link_to 'Back', books_path %>

和模型:

   class Book < ActiveRecord::Base
            attr_accessible :abstract, :status, :titel, :user_tokens, user_ids,        :chapters_attributes

     has_and_belongs_to_many :users
     attr_reader :user_tokens

     has_many :chapters, :dependent => :destroy, :autosave => true, :order => 'slot'

     validates :title, :presence => true

     accepts_nested_attributes_for :chapters, :allow_destroy => true

     after_initialize :init
     def init
       self.status = false if self.status?
     end

     def user_tokens=(ids)
       self.user_ids = ids.split(",")
     end

   end
   end
4

1 回答 1

0

您的部分将不知道您在控制器中设置的实例变量。渲染部分时,您必须将它们作为本地人传递

render :partial => "form", :locals => {:book => @book}

在你的部分,使用book而不是@book

<%= form_for(book) do |f| %>
   <% if book.errors.any? %>
   <div id="error_explanation">
   <h2><%= pluralize(book.errors.count, "error") %> prohibited this book from being saved:</h2>
于 2013-07-10T21:59:56.403 回答