rails add_column具有默认值但默认值不生效

时间:2012-10-08 09:10:17

标签: ruby-on-rails-3

我的rails版本是3.2.8并使用默认数据库。 这是我的迁移代码:

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

I find a explaination about :default option here 正如它所说,当我创建一个 新的LineItem,它应该有一个默认的数量= 1,但这是我从rails console得到的:

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

当我从数据库中获取LineItem时,数量字段为零   太

这是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

1 个答案:

答案 0 :(得分:3)

您的迁移应该可以正常运行。根据您的架构,虽然看起来它实际上没有生效,因为t.integer "quantity"没有默认值。

quantity架构中的行应如下所示:

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

确保您实际上已经运行了迁移(bundle exec rake db:migrate),如果这不起作用,则回滚(bundle exec rake db:rollback)并再次运行迁移(如@ surase.prasad建议的那样)。< / p>