嘿,我有另一个问题;)
当我尝试在我的应用中创建一本新书时,它总是说
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
答案 0 :(得分: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>