2012-10-08 80 views
1

我的rails版本是3.2.8并使用默认数据库。 这是我的移民代码:rails add_column具有默认值但默认值不生效

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,但这里是我从铁轨控制台中看到:

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 
+0

回滚迁移并重新运行。 –

+0

我有类似的问题。我在迁移中有两个“change_column”语句,第二个语句对模式没有任何影响。,对我而言,我的两个“change_column”语句分为两个迁移。 –

回答

1

您应该迁移工作正常。根据你的模式,尽管它看起来并没有真正起作用,因为t.integer "quantity"没有默认值。

在架构quantity行应该是这样的:

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

确保您已实际运行迁移(bundle exec rake db:migrate),如果不工作,然后回滚(bundle exec rake db:rollback),然后运行再次迁移(如@ surase.prasad建议)。

+0

是的,回滚和再次迁移,它的工作,谢谢 – xsj0jsx