Rails 3 迁移:布尔值(mysql 与 postgreSQL)
我正在尝试在我的论坛主题上添加“粘性”选项。这就是我的迁移的样子
def self.up
add_column :topics, :sticky, :boolean, :null => false, :default => false
end
def self.down
remove_column :topics, :sticky
end
这在 mysql 本地工作得很好,但是当我将更改推送到 heroku (使用 PostgreSQL)时,这就是我在使用控制台时得到的结果
>> t.sticky
=> "f"
>> t.sticky.class
=> String
>> t.sticky = true
=> true
>> t.sticky.class
=> TrueClass
为什么此属性的默认值是字符串?
编辑: 如果我保存对象,它不会改变粘性属性,即它仍然是“f”。
I'm trying to add a "sticky" option on my forum topics. This is how my migration looks like
def self.up
add_column :topics, :sticky, :boolean, :null => false, :default => false
end
def self.down
remove_column :topics, :sticky
end
This works perfect locally on mysql, but when I push the changes to heroku (which uses PostgreSQL), this is what I get when using the console
>> t.sticky
=> "f"
>> t.sticky.class
=> String
>> t.sticky = true
=> true
>> t.sticky.class
=> TrueClass
Why is the default value of this property a String?
Edit:
And if I save the object, it doesn't change the sticky property, i.e. it's still "f".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 psql 中,布尔值显示为
t
或f
。根据数据库驱动程序,它们会转换为布尔值或保留在字符串表示形式中。PHP 中的 PDO 驱动程序执行相同的操作。 (或者习惯了,无论如何......我隐约记得它在最新版本中不再这样做了。)
In psql, booleans are displayed as
t
orf
. Depending on the DB driver, these get converted to booleans or left in their string representation.The PDO driver in PHP does the same thing. (Or used to, anyway... I vaguely recall it no longer does in its latest version.)
除非您在 RoR 或数据库驱动程序中发现错误,否则按照 Denis 的建议,您可以将读取访问器定义(覆盖)为:
这会将已知的“假”值转换为真正的 ruby 布尔值。
我记得至少有两个 gem 可以连接到 PostgreSQL 数据库。也许你可以使用另一个?
并且您确定数据库中的列没有定义为字符串吗?我知道在你的迁移中它是布尔值,但也许某个地方出了问题?
Unless you find a bug in RoR or the database driver, as suggested by Denis, you may define (override) the read accessor as:
This will convert known 'false' values to real ruby booleans.
I recall there were at least two gems to connect to PostgreSQL databases. Maybe you can use the other one?
And are you sure that the column in the database is not defined as String? I know that in your migration it's boolean, but maybe something somewhere went wrong?
我不确定问题是什么,但我只是回滚迁移并再次运行它,这次成功了。只是将其放在这里以防其他人遇到类似的问题。
谢谢你们的帮助。
I'm not sure what the problem was, but I just rolled back the migration and ran it again, and it worked this time. Just putting this here in case someone else encounters a similar problem.
Thanks for your help guys.