开发者

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) %>
&l开发者_开发知识库t;% else %> 
    <%= image_tag('off.png', :alt => "Inactive", :border => 0) %>
<% end %>

Shouldn't the first method work or am I missing something?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜