Slick23
Slick23

Reputation: 5897

Testing for false in Rails 3

I'm trying to test whether a check_box in my rails app is checked.

Here's the code in my model:

attr_accessor :post_to_facebook

before_save :to_facebook?

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

And in the view:

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

Checked or not, Rails is always evaluating to_facebook as true. For example, this is what was posted in the log: "post_to_facebook"=>"0", but it still evaluated as true. Can anyone spot what's wrong with the code?

Upvotes: 0

Views: 118

Answers (1)

tomferon
tomferon

Reputation: 4991

In Ruby, only false and nil are evaluated as false. That means "0" (or even 0) is "truthy". What you can do is :

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

Upvotes: 2

Related Questions