Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 3.0.3 check if boolean value is true

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?

like image 723
andkjaer Avatar asked Nov 25 '10 09:11

andkjaer


People also ask

How do you know if a Boolean value is true?

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!

Is true or false in Ruby?

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.”


2 Answers

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.

like image 79
nonopolarity Avatar answered Sep 30 '22 12:09

nonopolarity


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 %>
like image 24
rwilliams Avatar answered Sep 30 '22 12:09

rwilliams