Amit
Amit

Reputation: 3990

rails 3.0.5 issue with nil variables!

I have a variable in my partial called title. If I do:

<% if title.nil? %>
  # stuff here
<% end %>

Then I get an error that title in not a known variable or method! What is wrong?

Upvotes: 0

Views: 277

Answers (2)

Pan Thomakos
Pan Thomakos

Reputation: 34340

If your variable is not defined then you'll get this error.

A variable in a partial can be defined by passing it as a local variable:

<%= render :partial => 'my_partial', :locals => { :title => 'My Title' } %>

Or by defining it in the partial:

<% title = nil %>
<% if title.nil? %>
  # Do stuff here.
<% end %>

You can also use instance variables in your partial, like @title and they don't need to be defined because they will always default to nil.

If you want to check if your variable is defined, then do the following:

<% if defined?(title) %>
  # Do stuff here.
<% end %>

Upvotes: 2

raid5ive
raid5ive

Reputation: 6642

Where is your variable defined? If it is set in a controller it should be an instance variable, which is prepended with @ like @title. If title is actually declared in your partial, you shouldn't have any issues.

Upvotes: 2

Related Questions