xsj0jsx
xsj0jsx

Reputation: 169

rails add_column with default value but the default value don't take effect

My rails version is 3.2.8 and use the default database. This is my migration code:

class AddQuantityToLineItem < ActiveRecord::Migration
  def change
    add_column :line_items, :quantity, :integer,:default=>1
  end
end

I find a explaination about :default option here and as it said,when i create a new LineItem ,it should have a default quantity=1,but here is what i get from rails console:

lineb=LineItem.new
#<LineItem id: nil, product_id: nil, cart_id: nil, created_at: nil, updated_at: nil, quantity: nil>

And when i get LineItem from the database,the quantity field is nil too.

And here is the db/schema.rb :

ActiveRecord::Schema.define(:version => 20121008065102) do

  create_table "carts", :force => true do |t|
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

  create_table "line_items", :force => true do |t|
    t.integer  "product_id"
    t.integer  "cart_id"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
    t.integer  "quantity"
  end

  create_table "products", :force => true do |t|
    t.string   "title"
    t.text     "description"
    t.string   "image_url"
    t.decimal  "price",       :precision => 8, :scale => 2
    t.datetime "created_at",                                :null => false
    t.datetime "updated_at",                                :null => false
  end

end

Upvotes: 2

Views: 8964

Answers (1)

Chris Salzberg
Chris Salzberg

Reputation: 27374

Your migration should work fine. Based on your schema though it looks like it hasn't actually taken effect, since t.integer "quantity" has no default value.

The line in the schema for quantity should look like this:

t.integer  "quantity",   :default => 1

Make sure you have actually run your migration (bundle exec rake db:migrate), and if that doesn't work then rollback (bundle exec rake db:rollback) and run the migration again (as @surase.prasad suggested).

Upvotes: 4

Related Questions