Martin Petrov
Martin Petrov

Reputation: 2643

Update a column, all rows

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 console? I've been searching google for the past hour but I can't find anything.

I know how to do it for a single object, but not for all rows of a model.

Foo.find(1).update_attribute(:myattribute, 'value')

Upvotes: 78

Views: 49578

Answers (4)

Jimmy Huang
Jimmy Huang

Reputation: 4312

Try this:

Foo.update_all(some_column: "bar")

This will generate SQL query to database:

UPDATE "foos" SET "some_column" = "bar"; 

Upvotes: 143

wiseland
wiseland

Reputation: 1050

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

Upvotes: 2

jiahut
jiahut

Reputation: 1531

you can do like this:

Foo.update_all(new_column: "bar")

Upvotes: 3

stephenmurdoch
stephenmurdoch

Reputation: 34623

Since you already created the new field in a previous migration, create a brand new migration:

rails g migration UpdateFoos

Modify the migration:

def self.up    
  say_with_time "Updating foos..." do
    Foo.find(:all).each do |f|
      f.update_attribute :myattribute, 'value'
    end
  end
end

# from command line
Rake db:migrate

Let me know if this works, it might need a few adjustments. See rails docs for more:

Upvotes: 25

Related Questions