2011-11-27 60 views
0

我试图测试我的Rails应用中是否有check_box被选中。在Rails中测试false 3

这里是在我的模型代码:

attr_accessor :post_to_facebook 

before_save :to_facebook? 

def to_facebook? 
if self.post_to_facebook 
    // do stuff 
end 
end 

并在视图:

<div class="field"> 
    <%= f.check_box :post_to_facebook, :checked => 'checked' %><%= f.label :post_to_facebook %> 
</div> 

经过与否,Rails的一直在评估to_facebook为真。例如,这是日志中发布的内容:"post_to_facebook"=>"0",但它仍然被评估为true。任何人都可以发现代码有什么问题吗?

回答

2

在Ruby中,只有falsenil被评估为false。这意味着"0"(或甚至0)是“truthy”。你可以做的是:

def to_facebook? 
    if self.post_to_facebook.eql? 'checked' 
    # your stuff 
    end 
end