2013-07-10 46 views
0

嘿從來就得到了另一個問題;)未定義的方法`MODEL_NAME」的NilClass:類,但IST初始化

當我嘗試在我的應用程序創建一個新的書它總是說

undefined method "model_name" for NilClass:Class

我發現,它必須是在的form_for功能未初始化的PARAM ......在這裏我的代碼:

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 

我不知道爲什麼它應該是未初始化,一切正常之前,我改變了圖書和用戶之間的一些關係,但我有shoudn't是失敗要麼?

編輯:

應用程序/視圖/書籍/ 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 
+0

是什麼應用程序/視圖/書籍/ new.html.erb看喜歡? –

+0

您是否也可以使用您的Book模型的外觀? – dasnixon

+0

我不知道這是否是一個模型。您可以隨時使用調試器並在呈現之前查看它的外觀 – smile2day

回答

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> 
+0

我沒有得到你的解決方案的工作,我在哪裏必須粘貼部分渲染的線完全? – Enno

+0

在您的books/new.html.erb中。第2行 – usha

+0

然後我得到這個錯誤:未定義的局部變量或方法'書'爲#<#Class:0x462cbd0>:0x28c1e68> – Enno

相關問題