Ren*_*ler 5 ruby-on-rails ruby-on-rails-3
我在使用Rails和ActiveRecord中的mysql位时遇到问题.我们存储了一些已发布的Localities状态.
`published` bit(1) NOT NULL
Run Code Online (Sandbox Code Playgroud)
我把它搭建published:binary在铁轨上.
Locality.first.published回报"\x01".
如何让rails将此字段视为布尔值?
有一个staled Ticket,但黑客ActiveRecord不是一个真正的选择. https://rails.lighthouseapp.com/projects/8994/tickets/6102-activerecord-boolean-support-with-bit1-mysql-data-type
您可以覆盖已发布属性的属性读取器:
class Locality < ActiveRecord::Base
# overwrite the attribute reader of the published attribute
def published
self.read_attribute(:published) == "\x01" ? true : false
end
end
Run Code Online (Sandbox Code Playgroud)
UPDATE
或者为您的布尔返回值生成一个方法
class Locality < ActiveRecord::Base
def to_boolean
self.published == "\x01" ? true : false
end
end
Run Code Online (Sandbox Code Playgroud)
所以你可以打电话:
Locality.first.published.to_boolean => true || false
Run Code Online (Sandbox Code Playgroud)
但我认为第一个解决方案(覆盖属性读取器)更好.