NoMethodError in Posts#new

送分小仙女□ 提交于 2019-12-12 17:50:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!