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
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.
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.
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)
I believe you can just do @element.attribute?
(e.g. @element.link?
)
(I suppose we could call it "magic attributes".)
This checks for
Exactly what you want.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With