Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Variable to Partial - undefined local variable or method error

Here is the code in my view to call the partial:

<%= render(:partial => "tabs", :locals => {:class_Name => "Science", :y => 36}) %> 

and now here is what's in _tabs.html.erb:

<div> <h1> <%= class_Name %> </h1> </div> 

I expect HTML output of:

<div> <h1> Science </h1> </div> 

But instead I get the error:

undefined local variable or method `class_Name' for #<#<Class:0x007f873b156c28>:0x007f873b1f9540> 

I have closed and restarted Aptana (the IDE I use), and restarted the server multiple times

Thanks in advance for your time.

like image 216
rishim3 Avatar asked Apr 26 '13 05:04

rishim3


2 Answers

I've noticed that if I did not include 'partial:' before my partial path, like so:

<%= render 'my_partial', :locals => {:class_Name => "Science", :y => 36} %> 

I was required to use the hash+symbol in my partial to access the desired values as others have noted.

<div> <h1> <%= locals[:class_Name] %> has a y value of <%= locals[:y] %></h1> </div> 

However, including 'partial:' before my partial path:

<% render partial: 'my_partial', :locals => {:class_Name => 'Science', :y => 36 } %> 

...allowed me to simply call the hash values directly.

<div> <h1><%= class_Name %> has a y value of <%= y %></h1> </div> 

Just something to keep in mind, this issue tripped me up for awhile when trying to send the locals hash to my partial.

like image 108
MFarmer Avatar answered Sep 22 '22 22:09

MFarmer


If you are using the term partial: in your render, for example like so:

<% render partial: 'your_partial', locals: {foo: 'Biggs', bar: 'Wedge'} %>

Then your locals will be available simply as foo and bar, directly accessibly thus:

<%= foo %> //returns Biggs  <%= bar %> //returns Wedge 

However, If you are NOT using the term partials: in your render, for example like so:

<% render 'your_partial', locals: {foo: 'Biggs', bar: 'Wedge'} %>

Then your locals will be available as members of locals, accessible thus:

<% locals[:foo] %> //returns Biggs <% locals[:bar] %> //returns Wedge 
like image 20
Monarch Wadia Avatar answered Sep 21 '22 22:09

Monarch Wadia