27

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?

1
  • 2
    I know you already have accepted an answer, but I wonder, what do you mean by "does not work"? Also, remember that 'true' in ruby means "everything (!) except false and nil". For example 0, "0", empty array and so on, all represent truth. Maybe that was the problem? Commented Nov 25, 2010 at 13:13

3 Answers 3

66

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Just as an aside, rails adds in the <attribute>? method for boolean fields. This will return false if the value is set to false (ie 0/f/whatever) or nil. So, if you have an active attribute that is based on a boolean database field, then .active? should work. Generally though, it's better to just say "if item.active" as 動靜能量 suggests.
2

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 %>

Comments

0

The other way is using single line if else

<%= active ? here is your statement for true : here is your statement for false %>

For active? to work there should be an def active? method in your item object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.