2

我正在做Rails 入门教程,当我从 shell 运行本地服务器时,我得到了这个:

`NoMethodError in Posts#new` `/_form.html.erb where line #1 raised:
`undefined method `model_name' for NilClass:Class

那是提取的源代码(在第 1 行附近):

1: <%= form_for @post do |f| %>
2:  <% if @post.errors.any? %>
3:  <div id="errorExplanation">
4:      <h2><%= pluralize(@post.errors.count, "error") %> prohibited

我刚开始使用 Ruby on Rails,但不知道发生了什么。我究竟做错了什么?

4

3 回答 3

3

您看到的错误消息意味着您有一些包含nil对象而不是您期望的实际对象的变量。

虽然错误消息没有明确引用这一点,但您的@post变量很可能是 nil。

为什么是零?鉴于这里的代码,这几乎是不可能的。请PostsController#new同时发布您的操作。

于 2013-09-01T11:31:19.803 回答
2

修复在 posts_controller.rb中,添加下一个代码

def new @post = Post.new 结束

祝你好运

于 2013-09-20T06:14:21.870 回答
1
// Make sure to use model declaration inside your method to check the error logs

class PostsController < ApplicationController

def new
@post = Post.new
end
于 2014-01-17T05:28:10.687 回答