检查Rails中的实例变量

时间:2015-09-16 23:58:29

标签: ruby-on-rails ruby

我不明白我必须如何更改if (condition)以检查此变量是否存在。

<%= 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 个答案:

答案 0 :(得分:1)

假设location采用present?方法,通常会使用<% if @article.location.present? %> ... <% end %> 方法实现此目的:

nil?

如果你想对它更严格,你可以替换present?false返回@article表示空字符串,这通常是你想要的。)

如果您不确定location是否使用respond_to?方法,则可以先使用<% if @article.respond_to?(:location) && @article.location.present? %> ... <% end %> 进行测试:

details summary::-webkit-details-marker {
    background: url(/images/toggle-expand.png) center no-repeat;
    color: transparent;
}
details[open] summary::-webkit-details-marker {
    background: url(/images/toggle-collapse.png) center no-repeat;
    color: transparent;
}