Reputation: 7381
I'm trying to figure out how to run a migration that prepends a string to the beginning of a column. In this specific case I have a column called url
that currently stores everything after the domain (e.g. /test.html
). However I now want to prepend a single string http://google.com
to the beginning of the url. In the case of this example, the resulting string value of url for this entry would be http://google.com/test.html
.
How can I accomplish this with a migration?
Upvotes: 0
Views: 124
Reputation: 29349
you could use migration or a rake task to do this.
If you want to run it as a migration,
def up
execute("update TABLE set url = 'http://google.com' || url") // '||' concatenates string in postgres. Use the function provided by your database
end
def down
//this is little tricky. I would advice to leave this empty
end
Upvotes: 2
Reputation: 16064
I'm not sure this really qualifies as something you should put into a migration; generally, migrations change the structure of your database, rather than change the format of the data inside of it.
The easiest and quickest way to do this would not be to futz around in your database at all, and instead just make the url
method of that model return something like "http://google.com#{read_attribute(:url)}"
. If you really want to change the data in your database, I'd make a rake task to do it, something like:
namespace :data do
task :add_domain do
Model.each do |model|
model.url = "http://google.com#{model.url}" if model.url !~ /google\.com/
model.save if model.changed?
end
end
end
If this must be a migration for you, then your migration's up
would look very similar to the internals of that rake task. (Or it would call that rake task directly.)
Upvotes: 3