Reputation: 1034
I have a User model with a draft_record
boolean column which has a default of true
. When creating records they are created with draft_record
: false
rather than true
. This worked when the field was called draft however then the draft association and draft attribute assignment methods clashed resulting in the draft attribute being unsettable. Am I doing something wrong? I have had this problem before and just worked around it by reverting to what worked.
Ruby: 1.9.3-p327
Ruby on Rails: 3.2.12
DBMS: Postgres
Relevant migration:
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
Resultant schema
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
Creating a user object:
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 >
Upvotes: 0
Views: 1738
Reputation: 1034
This problem was caused by a default_scope
with the conditions hash set to draft_record: false
. This forced any record being added through active record to set draft_record
to false.
Upvotes: 3
Reputation: 47
The default value is set at DB level. So the insert query will not generate the default. Check the records inserted if they have correct default value set.
Upvotes: 0