2013-04-05 91 views
1

我有一个用状态标志(这是一个tinyint(1))定义的mysql表。 但是,当我尝试检查值是真还是假时,我似乎得出了错误的结果。也就是说,它不会看到该值作为一个合法的真或价值,而是测试的,如果它不是“无”或类似的 - 因此我的“似乎没有工作”Ruby TinyInt(1)?

results.each_hash do |row| 
# What I tried 

# (a) 
if row['status'] 
    # do something - doesn't seem to work 
end 

# (b) 
if row['status'].to_i == 1 
    # this seems correct 
end 

# (c) 
if row['status'] == false 
    # doesn't seem to work 
end 
end 

什么是正确的方法检查这个值(tinyint(1)),因为它应该是Ruby中的TrueClass或FalseClass;然而(c)本身不起作用。

这是我所使用的参考 - 我假定这应该在导轨和红宝石本身适用(除非ActiveRecord的做的工作) - http://www.orthogonalthought.com/blog/index.php/2007/06/mysql-and-ruby-on-rails-datatypes/

+0

TinyINT get的解释在大多数语言中C#等是“布尔”,抱歉,Ruby也是如此(应该将它看作TRUECLASS或FALSECLASS) – 2013-04-05 10:38:03

回答

2

active_record-3.2.13abstract_mysql_adapter.rb代码行96:

# By default, the MysqlAdapter will consider all columns of type <tt>tinyint(1)</tt> 
    # as boolean. If you wish to disable this emulation (which was the default 
    # behavior in versions 0.13.1 and earlier) you can add the following line 
    # to your application.rb file: 
    # 
    # ActiveRecord::ConnectionAdapters::Mysql[2]Adapter.emulate_booleans = false 
+0

谢谢 - 所以Active Record认为它是Bool和Ruby(独立的)认为它是简单的int 。谢谢 – 2013-04-05 10:59:09

+0

Ruby本身不会说数据库。如果您使用的是ActiveRecord,无论您是在Rails中还是仅在非Rails项目中使用ActiveRecord gem,都应该应用相同的数据转换。如果你在Rails之外使用ActiveRecord,你可能会缺少Rails提供的一些配置。如果你根本没有使用ActiveRecord(例如mysql2 gem),那么你必须参考该文档。 – 2013-04-05 13:24:30

相关问题