Long Le Long Le - 1 month ago 10
Ruby Question

How to pass instance variables from controller to render partial in Ruby

I am having trouble passing an instance variables (@article) from a controller (articles_controller.rb) to a partial render (_form.html.erb) in Ruby.

Here is the error from being sent back:

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


Any help would be appreciated

Answer

You should do like this, removing @. You are passing it to local variable article so you could access it with article not @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>

For more info, please take a look at passing-local-variables