好吧,我一直在这里寻找一个与我完全相同的问题,但我找不到,所以我不得不自己问。我正在按照此处的指南进行操作:http://guides.rubyonrails.org/getting_started.html
我在编辑文章页面遇到了这样的错误:“undefined method ‘errors’ for 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:in block in _app_views_articles_edit_html_erb___778692675__618464548
app/views/articles/edit.html.erb:3:in _app_views_articles_edit_html_erb___778692675__618464548
这是我的 Action Controller
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, 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>
<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
的回答之外,您可能还需要考虑错误本身:
"undefined method `errors' for nil:NilClass"
您返回的是一个异常,因为您正试图在 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 %>
关于ruby-on-rails - 为 nil :NilClass Ruby on Rails Guide 获取未定义的方法 `errors',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24293838/