Ruby-on-rails rails 3.0.3 检查布尔值是否为真
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4275616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
rails 3.0.3 check if boolean value is true
提问by andkjaer
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?
第一种方法不应该起作用还是我错过了什么?
回答by nonopolarity
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.
也会起作用。 if item.active?仅当存在名称实际上为 的方法时才有效active?,这通常是命名返回 true 或 false 的方法的约定。
回答by rwilliams
This should work for you assuming item.activeis truly a boolean value. Unless there is a method defined for item.active?your example will only return a no-method error.
假设item.active它确实是一个布尔值,这应该对你有用。除非为item.active?您的示例定义了方法,否则只会返回无方法错误。
<% if item.active %>
<%= image_tag('on.png', :alt => "Active", :border => 0) %>
<% else %>
<%= image_tag('off.png', :alt => "Inactive", :border => 0) %>
<% end %>
回答by gsumk
The other way is using single line if else
另一种方法是使用单行 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.
为了active?工作def active?,您的项目对象中应该有一个方法。

