xph
xph

Reputation: 752

Best way to populate a new attribute (new database column) of existing Rails models?

I've just added a new column to an existing table in my database:

class AddMoveableDateToDocument < ActiveRecord::Migration
  def change
    add_column :documents, :moveable_date, :datetime
  end
end

In my Rails model I want the moveable_date attribute to be set to a default value upon creation, and the application will be able to change this date later. So, something like:

class Document < ActiveRecord::Base
  before_create :set_moveable_date
  def set_moveable_date
    self.moveable_date ||= self.created_at
  end
end

Now, the existing models that are already saved into the database will not have this moveable_date set yet (the value is nil). How do I run through all my existing models and populate the moveable_date attribute with its default value? What is the easiest/best practice way? Can be in the application code itself, in the console, in the terminal, or otherwise. Thanks!

Upvotes: 0

Views: 134

Answers (2)

Kites
Kites

Reputation: 1168

That's a good suggestion!

Another way is to add the line before_save :set_moveable_date to your model. It won't accomplish the transition immediately, but if your data is updated on a regular basis, it'd work.

Upvotes: 0

sevenseacat
sevenseacat

Reputation: 25029

You will get a lot of opinionated answers on this one. Some will suggest the console, some will suggest a one-time rake task.

I would suggest doing it as part of the migration that adds the column. After adding the column, you can run Document.reset_column_information so that the Rails app picks up on your new column, and then iterate through the existing document records and set the moveable date as appropriate.

Or if it's as simple as setting the moveable date to the created_at date, you can use something like Document.update_all("moveable_date = created_at") instead of iterating over them.

Upvotes: 1

Related Questions