I want to check if a value is true or false.
<% if item.active? %>
<%= image_tag('on.png', :alt => "Active", :border => 0) %>
<% else %>
<%= image_tag('off.png', :alt => "Inactive", :border => 0) %>
<% end %>
That doesn't work, but this works?
<% if item.active == true %>
<%= image_tag('on.png', :alt => "Active", :border => 0) %>
<% else %>
<%= image_tag('off.png', :alt => "Inactive", :border => 0) %>
<% end %>
Shouldn't the first method work or am I missing something?
To check if a value is of boolean type, check if the value is equal to false or equal to true , e.g. if (variable === true || variable === false) . Boolean values can only be true and false , so if either condition is met, the value has a type of boolean. Copied!
Every object in Ruby has a boolean value, meaning it is considered either true or false in a boolean context. Those considered true in this context are “truthy” and those considered false are “falsey.” In Ruby, only false and nil are “falsey,” everything else is “truthy.”
if this line works:
if item.active == true
then
if item.active
will also work. if item.active?
works only if there is a method whose name is actually active?
, which is usually the convention for naming a method that returns true or false.
This should work for you assuming item.active
is truly a boolean value. Unless there is a method defined for item.active?
your example will only return a no-method error.
<% if item.active %>
<%= image_tag('on.png', :alt => "Active", :border => 0) %>
<% else %>
<%= image_tag('off.png', :alt => "Inactive", :border => 0) %>
<% 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