Rubyのコントローラ(articles_controller.rb)から部分的なレンダリング(_form.html.erb)にインスタンス変数(@article)を渡す際に問題があります。Rubyでコントローラからインスタンス変数をpartialに渡す方法
`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は正しかった、新しく@articleを初期化するのを忘れていましたが、私はそれを初期化しました –