Check instance variable in Rails

I don't understand how I must change an if (condition) to check for the presence of this variable.

<%= if (@article.location != nil) %>
<%= image_tag "http://maps.google.com/maps/api/staticmap?size=450x300&sensor=false&zoom=16&markers=#{@article.location.latitude}%2C#{@article.location.longitude}" %>
<% end %>

Upvotes: 0

Views: 66

Answers (1)

ahmacleod
ahmacleod

Reputation: 4310

Assuming that @article has a location method, one typically uses the present? method for this purpose:

<% if @article.location.present? %>
    ...
<% end %>

You can substitute nil? if you want to be more strict about it (present? returns false for an empty string, which is usually what you want).

If you're not sure that @article even has a location method, you can test for it first, using respond_to?:

<% if @article.respond_to?(:location) && @article.location.present? %>
    ...
<% end %>

Upvotes: 1

Related Questions