【发布时间】:2017-02-22 04:49:30
【问题描述】:
我在将实例变量 (@article) 从控制器 (articles_controller.rb) 传递到 Ruby 中的部分渲染 (_form.html.erb) 时遇到问题。
这是被发回的错误:
`undefined method `errors' for nil:NilClass`
articles_controller.rb:
class ArticlesController < ApplicationController
def new
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to @article
else
render 'new'
end
end
def update
@article = Article.find(params[:id])
if @article.update(article_params)
redirect_to @article
else
render 'edit', :article => @article
end
end
def show
@article = Article.find(params[:id])
end
def index
@articles = Article.all
end
private
def article_params
params.require(:article).permit(:title, :text)
end
end
new.html.erb
<h1>New Article</h1>
<%= form_for :article, url: articles_path do |f|%>
<%= render partial: "form", :locals => {:article => @article} %>
<% end %>
<% link_to 'Back', articles_path %>
_form.html.erb
<% 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_messeages.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>
任何帮助将不胜感激
【问题讨论】:
-
你有没有在你的新方法中初始化@article?
-
你试过我下面的答案了吗?
-
araratan,我试过了,但似乎没有奏效。 Shabini Rajadas,没错,我忘了在 new 中初始化 @article,我只在 create 中初始化了它
-
@aratatan,谢谢,我现在明白了。您将控制器的实例变量作为局部变量传递。现在一切正常
标签: ruby-on-rails ruby ruby-on-rails-4