问题
I have record in my db that is a boolean field (true/false).
The field is archived. When archived is true all these work great to output true:
Rails.logger.info @commentable.archived
Rails.logger.info @commentable.archived?
Rails.logger.info !!@commentable.archived?
BUT when the archived is false, it outputs nothing for either of the above. How can I get an output of false when the field is FALSE?
Thanks
回答1:
Try .to_s
on the field?
irb(main):001:0> false.to_s
=> "false"
irb(main):002:0> true.to_s
=> "true"
irb(main):003:0>
回答2:
I prefer to use .inspect
for doing output to logging. I find its output more useful if you get a nil value.
ruby-1.8.7-p302 > nil.to_s
=> ""
ruby-1.8.7-p302 > nil.inspect
=> "nil"
ruby-1.8.7-p302 > false.to_s
=> "false"
ruby-1.8.7-p302 > false.inspect
=> "false"
ruby-1.8.7-p302 >
回答3:
false.to_s == 'false'
, but Rails.logger.info
seems to do the wrong thing here:
> puts true
true
> puts false
false
> Rails.logger.info true
true
> Rails.logger.info false
来源:https://stackoverflow.com/questions/4728130/ruby-rails-dealing-with-a-boolean-false-it-outputs-nothing