Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 717
Eric Norcross Avatar asked Oct 06 '13 18:10

Eric Norcross


People also ask

How do you check if data attribute exists in Javascript?

Use the hasAttribute() method to check if a data attribute exists, e.g. if (el. hasAttribute('data-example')) {} . The hasAttribute method returns true if the provided attribute exists, otherwise false is returned.

How do you check attributes in python?

To check if an object in python has a given attribute, we can use the hasattr() function. The function accepts the object's name as the first argument 'object' and the name of the attribute as the second argument 'name. ' It returns a boolean value as the function output.


3 Answers

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) 
like image 83
ck3g Avatar answered Sep 25 '22 05:09

ck3g


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.

like image 44
ahnbizcad Avatar answered Sep 22 '22 05:09

ahnbizcad


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
like image 31
OneChillDude Avatar answered Sep 22 '22 05:09

OneChillDude