Jeremy Thomas
Jeremy Thomas

Reputation: 6694

Rails partial with optional variable not working

I'm not sure what's going on here but the following throws an error on render:

<%= render 'clients/clients_table', special: true %> 

and in my partial I have:

<% if defined?(:special) %>
    <p><%= special %></p> <!-- line with error -->
<% else %>
    <p>No</p>
<% end -%>

This throw the error:

undefined local variable or method `special' for #<#<Class:0x007fa20fbb0310>:0x007fa20cb986a0>

When I try to display local_assigns.has_key?(:special) it also shows false. Any idea what's going on?

Upvotes: 2

Views: 634

Answers (2)

Matthieu Libeer
Matthieu Libeer

Reputation: 2365

defined?(:special) checks if the symbol :special is defined. It always is.

You want to check if the variable special is defined: defined?(special)

Upvotes: 1

engineersmnky
engineersmnky

Reputation: 29598

I always recommend sending variables under the locals: key rather than directly. Maybe try this:

<%= render 'clients/clients_table', locals: {special: true} %> 

Also in your partial this defined?(:special) is incorrect because it will always be truthy

defined?(:special)
#=> "expression" 

Instead use local_assigns e.g.

<% if local_assigns[:special] %>

Upvotes: 6

Related Questions