Rails ActiveRecord不尊重布尔值默认值



我有一个具有draft_record布尔列的用户模型,其默认值为true。创建记录时使用draft_record: false,而不是true。当该字段被称为draft时,这种方法是有效的,但是随后draft关联和draft属性分配方法发生冲突,导致draft属性不可设置。我做错了什么吗?我以前遇到过这个问题,只是通过恢复工作来解决它。

Ruby: 1.9.3-p327

Ruby on Rails: 3.2.12

DBMS: Postgres

相关迁移:

class AddDraftColumnToUsers < ActiveRecord::Migration
  def self.up
    add_column :users, :draft_record, :boolean, default: true
    add_column :users, :draft_id, :integer
    add_column :users, :current_id, :integer
  end
  def self.down
      ...
  end
end

合成模式

ActiveRecord::Schema.define(:version => 20130303002123) do
  create_table "users", :force => true do |t|
    t.datetime "created_at",                     :null => false
    t.datetime "updated_at",                     :null => false
    t.string   "name"
    t.boolean  "draft_record", :default => true
    t.integer  "draft_id"
    t.integer  "current_id"
  end
end

创建用户对象:

Loading development environment (Rails 3.2.12)
1.9.3-p327 :001 > u = User.create(name: "Jon")
   (0.0ms)  begin transaction
  SQL (28.8ms)  INSERT INTO "users" ("created_at", "current_id", "draft_id", "draft_record", "name", "updated_at") VALUES (?, ?, ?, ?, ?, ?)  [["created_at", Sun, 03 Mar 2013 00:42:04 UTC +00:00], ["current_id", nil], ["draft_id", nil], ["draft_record", false], ["name", "Jon"], ["updated_at", Sun, 03 Mar 2013 00:42:04 UTC +00:00]]
   (0.7ms)  commit transaction
 => #<User id: 1, created_at: "2013-03-03 00:42:04", updated_at: "2013-03-03 00:42:04", name: "Jon", draft_record: false, draft_id: nil, current_id: nil> 
1.9.3-p327 :002 > 

这个问题是由default_scope的条件哈希值设置为draft_record: false引起的。这将强制任何通过活动记录添加的记录将draft_record设置为false。

默认设置为DB级别。因此插入查询将不会生成默认值。检查所插入的记录是否有正确的默认值设置。

最新更新