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

36,042

Solution 1

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)

Solution 2

I believe you can just do @element.attribute? (e.g. @element.link?) (I suppose we could call it "magic attributes".)

This checks for

  • the attribute existing on the model
  • the value not being nil

Exactly what you want.

Solution 3

Try using the attributes hash. This hash will return a key => value mapping of all of an activerecord object's attributes.

if @element.attributes['link']
  # Here we are
else
  # default
end
Share:
36,042
Eric Norcross
Author by

Eric Norcross

Developer with over ten years of professional experience. Detail orientated, end-user focused, and a passion for solving complex problems. Experienced in front & back-end development, system architecture, UX design, ad trafficking – oh, and a background in graphic design

Updated on October 17, 2021

Comments

  • Eric Norcross
    Eric Norcross over 2 years

    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