Question

I have a database of links that all point to a specific site, but different pages on that site. Well the site's domain changed and I need to update my database to reflect that change. I only need to change the domain name, the rest of the link works fine.

My question is, can I use a rails migration to do this? To edit all fields in a column and update them? What would this look like?

I know there are other ways to approach it, but I want to explore the options I would have with a rails migration.

Thanks in advance!

Was it helpful?

Solution

Sure, you have two options. 1) You can write ActiveRecord code in migrations just like you would in a model, e.g.:

class ChangeDomainName < ActiveRecord::Migration
  def self.up
    YourModel.update_all "url = REPLACE(url, 'www.old-domain-name.com', 'www.new-domain-name.com')"
  end

  def self.down
    # ...
  end
end

One thing to remember in this scenario is that if you're changing e.g. column names or types in the same migration before update_all you need to do YourModel.reset_column_information after altering the table and before calling ActiveRecord methods on it.

2) You can use raw SQL with the "execute" method:

def self.up
  execute "UPDATE your_models SET url = REPLACE(url, 'www.old-domain-name.com', 'www.new-domain-name.com)"
end

Personally I prefer the first method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top