Update a column, all rows

前端 未结 4 1748

I added a new column to my table but I forgot to add the :default option. Now I want to populate that column on every single row.

Is there a way to do with using the con

4条回答
  •  感情败类
    2021-01-31 01:49

    Of course you can use smth like Foo.update_all(:myattribute => "value"), but it'll modify only already created data. To set default value for all "future" data it's a good way to create a separate migration like this:

    rails generate migration AddDefaultValueToFoo
    

    Modify new migration (for ex. myattribute has a string type) like this:

    class AddDefaultValueToFoo < ActiveRecord::Migration
      def self.up
        change_column :foos, :myattribute, :string, :default => "value"
        Foo.update_all(:myattribute => "value")
      end
    end
    

提交回复
热议问题