问题
I'm doing the Getting started with Rails tutorial and when I run the local server from shell I get this:
`NoMethodError in Posts#new` `/_form.html.erb where line #1 raised:
`undefined method `model_name' for NilClass:Class
That is the extracted source (around line #1):
1: <%= form_for @post do |f| %>
2: <% if @post.errors.any? %>
3: <div id="errorExplanation">
4: <h2><%= pluralize(@post.errors.count, "error") %> prohibited
I just started on Ruby on Rails and I can't figure out what is happening. What am I doing wrong?
回答1:
The error message, you are seeing means that you have some variable that contains a nil object instead of the actual object you expect.
While the error message doesn't explicitly reference this, it is likely your @post variable is nil.
Why is it nil? That's near impossible to say given the code here. Please post your PostsController#new action as well.
回答2:
The fix is into posts_controller.rb, add next code
def new @post = Post.new end
Good luck
回答3:
// Make sure to use model declaration inside your method to check the error logs
class PostsController < ApplicationController
def new
@post = Post.new
end
来源:https://stackoverflow.com/questions/18557861/nomethoderror-in-postsnew