ruby-on-rails – 为nil获取未定义的方法`errors’:NilClass Ru
好的,我一直在寻找一个与我完全一样的问题而且我找不到一个问题,所以我不得不自己问一下.我在这里遵循指南:
http://guides.rubyonrails.org/getting_started.html
我遇到了这个错误说:“我的编辑文章页面的nil:NilClass的未定义方法`错误’. 这是我提取的来源: <h1>Editing article</h1> <%= form_for :article,url: articles_path(@article),method: :patch do |f| %> <% if @article.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@article.errors.count,"error") %> prohibited this article from being saved: </h2> 这是我的追踪: app / views / articles / edit.html.erb:4:在_app_views_articles_edit_html_erb___778692675__618464548的块中 app / views / articles / edit.html.erb:3:in _app_views_articles_edit_html_erb___778692675__618464548 这是我的动作控制器 class ArticlesController < ApplicationController def new @article = Article.new end def edit @articles = Article.find(params[:id]) end def create @article = Article.new(article_params) if @article.save redirect_to @article else render 'new' end end def show @article = Article.find(params[:id]) end def index @articles = Article.all end def update @article = Article.find(params[:id]) if @article.update(article_params) redirect_to @article else render 'edit' end end private def article_params params.require(:article).permit(:title,:text) end end 这是我的edit.html.erb <h1>Editing article</h1> <%= form_for :article,method: :patch do |f| %> <% if @article.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@article.errors.count,"error") %> prohibited this article from being saved: </h2> <ul> <% @article.errors.full_messages.each do |msg| %><li><%= msg %></li> <% end %> </ul> </div> <% end %> <p> <%= f.label :title %><br> <%= f.text_field :title %> </p> <p> <%= f.label :text %><br> <%= f.text_area :text %> </p> <p> <%= f.submit %> </p> <% end %> 解决方法
变量定义
除了Arup的答案,你可能想要考虑的是错误本身:
你得到的是一个例外,因为你试图在一个nil类对象上调用一个方法.正如Arup指出的那样,这通常是由你调用@instance_variable而不首先定义它引起的 我想强调一下,你的错误说明问题是你的对象有一个未定义的方法.由于某些原因,大多数人会处理问题,因为您的方法未定义;实际上问题是你没有定义对象. – 固定 正如Arup所指出的,修复错误的方法是引用在edit方法中定义的@instance变量,如下所示: #app/controllers/articles_controller.rb Class ArticlesController < ApplicationController def edit @article = Article.find params[:id] end end #app/views/articles/edit.html.erb <%= @article.errors %> 您还需要考虑的其他事项如下: #app/views/articles/edit.html.erb <%= form_for @article do |f| %> # ... <% end %> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |