【问题标题】:Rails - Boolean field not saved on PostgreSQL / HerokuRails - 布尔字段未保存在 PostgreSQL/Heroku 上
【发布时间】:2011-12-09 04:48:12
【问题描述】:

遇到了一个奇怪的问题:

布尔字段未保存在 Heroku 上(本地工作正常)

详情:

  Rails 2.3 on Heroku (bamboo-ree-1.8.7).

迁移

  def self.up
   add_column :users, :send_contact_emails, :boolean, :default => false
  end

在 Heroku 上:

>> u = User.last
=> #<User id: 100, ......
>> u.send_contact_emails = true
=> true
>> u.save
=> true

>> x = User.last
=> #<User id: 100, ...
>> x.send_contact_emails
=> nil  <---------------------------- Why is this ?

当我在本地(Postgresql 8.4)执行此操作时,它按预期工作。

有什么想法吗?

编辑:

直接在数据库上运行一些测试:

>> ActiveRecord::Base.connection.execute("SELECT send_contact_emails from users where id = 100")[0]
=> {"send_contact_emails"=>nil}

>> ActiveRecord::Base.connection.execute("UPDATE users SET send_contact_emails=FALSE where id=100")
=> #<PGresult:0x7f76d7593580>

>> ActiveRecord::Base.connection.execute("SELECT send_contact_emails from users where id = 100")[0]
=> {"send_contact_emails"=>"f"}

所以问题出在 Rails 而不是 Postgresql...

【问题讨论】:

  • 不是很有帮助,但看起来像 stackoverflow.com/questions/7437789/… 的副本
  • 遗憾的是,该问题中建议的神奇解决方案(回滚/重新迁移)不起作用。
  • 很遗憾听到这个消息 - 这似乎是一个遥远的目标,但我认为无论如何还是值得一提
  • 你在 heroku 和 localy 上有相同的 Postgres 吗?

标签: ruby-on-rails postgresql activerecord heroku rails-postgresql


【解决方案1】:

确保重新启动应用。

http://devcenter.heroku.com/articles/rake

一旦您运行添加新列的迁移,您必须在 heroku 上使用“heroku restart”手动重新启动您的应用,以便 Rails 会接收更改。

【讨论】:

  • 我遇到了一个问题,simple_form 生成的布尔字段在 Heroku 上显示为文本字段。这个答案解决了这个问题。谢谢!
【解决方案2】:

看起来问题出在 RAILS 方面。

一旦我手动将值更新为 false:

ActiveRecord::Base.connection.execute("UPDATE users SET send_contact_emails=FALSE")

问题消失了。

(好像 rails 2.3.10 无法处理布尔字段中的“nil”..)

【讨论】:

  • 平心而论,我认为 nil 不应被视为真或假,因为它们都不是。这是一个非常笼统的词Nil is a word commonly used to mean nothing or zero; it is one of several names for the number 0. - 这是否意味着它没有价值或是否意味着它应该是错误的。 (en.wikipedia.org/wiki/Nil)
【解决方案3】:

Rails 中的布尔值使用 tinyint 列类型,因此在 DB 级别是 1/0。

API

Class
ActiveRecord::ConnectionAdapters::MysqlAdapter < AbstractAdapter

emulate_booleans

By default, the MysqlAdapter will consider all columns of type tinyint(1) 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 environment.rb file:

  ActiveRecord::ConnectionAdapters::MysqlAdapter.emulate_booleans = false

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 2022-08-18
    相关资源
    最近更新 更多