当前位置: 动力学知识库 > 问答 > 编程问答 >

migration - Add column to table and fix value for existing records in Rails

问题描述:

I want to add a column called "payment_type" into my "orders" table.

Here is the migration that I have so far:

def change

add_column :orders, :payment_type, :string

end

I want that payment_type to hold the value "normal" for all the records that currently are in the DB. However, not for the future records. I want no default value for future records. How can I do this?

网友答案:

As you just want to set values for all existing records, you can use update_all, which is much faster than looping over all instances of order, as it uses just database statements and doesn't instanciate all the orders:

def up
  add_column :orders, :payment_type, :string
  Order.reset_column_information
  Order.update_all(payment_type: 'normal')
end

def down
  remove_column :orders, :payment_type
end

update_all does not call any validations or triggers.

网友答案:
def change
  add_column :orders, :payment_type, :string
  Order.all.each do |order|
    order.update_attributes(:payment_type => 'normal')
  end
end
网友答案:

If you want to updated column stick with migration then above answers is awesome, But if you want to update column locally on your own machine so that when you shear code others unable to see updated attribute, simple go to Rails console and loop...

orders = Order.all

 orders.each do |o|
   o.update_attribute(:payment_type, 'normal')
 end

Rails 4

分享给朋友:
您可能感兴趣的文章:
随机阅读: