Rails - PostgreSQL / Heroku上没有保存的布尔字段

时间:2011-10-17 10:34:10

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

遇到一个奇怪的问题:

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

详细说明:

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

移植

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

On 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),它按预期工作。

有什么想法吗?

编辑:

直接在DB上进行一些测试:

>> 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 ......

3 个答案:

答案 0 :(得分:10)

确保重新启动应用。

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

运行添加新列的迁移后,您必须使用“heroku restart”在heroku上手动重新启动应用程序,以便Rails获取更改。

答案 1 :(得分:2)

看起来问题出在RAILS方面。

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

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

问题消失了。

(好像rails 2.3.10在布尔字段中无法处理'nil'。)

答案 2 :(得分:-1)

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