2

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
Community
  • 1
  • 1
xsj0jsx
  • 149
  • 3
  • 9
  • rollback the migration and rerun again. – Prasad Surase Oct 08 '12 at 09:18
  • i had a similar problem. I had two "change_column" statements in a migration and the second wasn't have any effect on the schema., What worked for me was splitting my two "change_column" statements into two migrations. – max pleaner Jan 22 '15 at 22:59

1 Answers1

4

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

tipycalFlow
  • 7,594
  • 4
  • 34
  • 45
Chris Salzberg
  • 27,099
  • 4
  • 75
  • 82