【问题标题】:undefined method `model_name' for NilClass:Class BUT ist initializedNilClass 的未定义方法“model_name”:类但未初始化
【发布时间】:2013-07-10 20:40:27
【问题描述】:

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

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

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

【问题讨论】:

  • app/views/books/new.html.erb 是什么样的?
  • 你能用你的 Book 模型展示一下吗?
  • 我也想知道这是不是模型。您始终可以使用调试器并在渲染之前检查它的外观
  • 在我更新的帖子中查看 new.html.erb 和 Book Model
  • 有时我会收到此错误:未定义的局部变量或方法 `user_ids' for #<0x46fb6a8>

标签: ruby-on-rails class model device null


【解决方案1】:

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

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>

【讨论】:

  • 我没有让你的解决方案工作,我必须在哪里准确粘贴部分渲染的行?
  • 在您的书籍/new.html.erb 中。第 2 行
  • 然后我得到了这个错误:未定义的局部变量或方法 `book' for #:0x28c1e68>
  • 你是加了render :partial =&gt; "form", :locals =&gt; {:book =&gt; @book}还是render "form", :locals =&gt; {:book =&gt; @book}
  • 我尝试了guides.rubyonrails.org/layouts_and_rendering.html 点 3.4.4 传递局部变量,但随后出现第一个错误......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-23
相关资源
最近更新 更多