2016-10-13 22 views
-1

Rubyのコントローラ(articles_controller.rb)から部分的なレンダリング(_form.html.erb)にインスタンス変数(@article)を渡す際に問題があります。Rubyでコントローラからインスタンス変数をpartialに渡す方法

`undefined method `errors' for nil:NilClass` 

Error

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> 

すべてのヘルプは

+0

を見てみてください、あなたの新しい方法で@articleを初期化することがありますか? –

+0

あなたは私の答えを試しましたか? – araratan

+0

アララタン、私はそれを試しましたが、それはトリックを行うように見えませんでした。 Shabini Rajadasは正しかった、新しく@articleを初期化するのを忘れていましたが、私はそれを初期化しました –

答えて

0

に依存します。あなたは、あなたがarticleない@articleでそれにアクセスすることができ、ローカル変数articleにそれを渡している。

<% 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> 

は、詳細情報については、passing-local-variables

0
def new 
    @article = Article.new 
end 




<%= render partial: "form", collection: @article %> 

あるいは

<%= form_for @article do |f|%> 
    <%= render 'form' %> 
<% end %> 

をいただければ幸いあなたは@を削除し、次のように行う必要があり、ニーズ

関連する問題