0

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

1 Answer 1

1

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 %>
Sign up to request clarification or add additional context in comments.

2 Comments

oh great, really helpful, can you add documentation about all like_this? methods
They all come from different places. nil? and respond_to? are part of core ruby. present? is part of ActiveSupport. There are many such meta methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.