What is the best way to check if an attribute exists and is set?

Eric Norcross picture Eric Norcross · Oct 6, 2013 · Viewed 31.3k times · Source

I have a common view that lists two different models. The only difference is that when setting the link_to action, one of the models has a link attribute and the other doesn't. I want to check if the link attribute exists, and if it does, check if it's set. I have the following which works, but I was wondering if there was a better way.

%li
  - if @element.has_attribute?("link") && @element.link
    = link_to @element.title, @element.link
  - else
    = link_to @element.title, @element

Answer

ck3g picture ck3g · Oct 6, 2013

You could use presence:

= link_to @element.title, (@element.link.presence || @element)

Or, if @element might not have link at all, you could use try:

= link_to @element.title, (@element.try(:link) || @element)