运行原始的SQL查询:
ActiveRecord::Base.connection.execute("UPDATE table_name set PhoneCol = REPLACE(PhoneCol, '(', '');")
ActiveRecord::Base.connection.execute("UPDATE table_name set PhoneCol = REPLACE(PhoneCol, ') ', '-');")
或你自己说的,使用update_all
:
Model.update_all("'PhoneCol' = REPLACE(PhoneCol, '(', '')")
Model.update_all("'PhoneCol' = REPLACE(PhoneCol, ') ', '-')")
如果你期待撤消更改,那么你可以创建两个耙任务:
namespace :phone_column do
desc "Update phone column from (xxx) -xxxx to xxx-xxxx"
task :update => :environment do
Model.update_all("'PhoneCol' = REPLACE(PhoneCol, '(', '')")
Model.update_all("'PhoneCol' = REPLACE(PhoneCol, ') ', '-')")
end
# NOTE: running this task can mess up the data if you have not run the previous task before
desc "Reverse xxx-xxxx to (xxx) -xxxx"
task :reverse => :environment do
Model.update_all("'PhoneCol' = CONCAT('(', SUBSTRING_INDEX(PhoneCol, '-', 1), ') ', SUBSTRING_INDEX(PhoneCol, '-', 2), '-', SUBSTRING_INDEX(PhoneCol, '-', -1))")
end
end
我会建议把这个与up
和down
方法迁移文件,但是这没有更新这样的数据的一个很好的方式,即迁移文件应该总是处理模式的变化,而不是在你的数据库中的数据更新。因为,随着项目的增长,当您创建新的迁移时,您将不会有任何其他选择在不参考其版本号的情况下对该迁移进行回滚,并且如果您(或其他人)错过了任何机会,您可能会面临生产服务器上严重的数据丢失。这就是为什么你的更新脚本应该在rake任务中(这不包括保证你的数据更新是可逆的)。
请看这里:https://stackoverflow.com/questions/4483049/how-to-execute-a-raw-update-sql-with-dynamic-binding-in-rails – mcfinnigan 2014-11-05 11:58:48
为什么你需要Rakefile?你可以使用Rails控制台做到这一点..对吗? – 2014-11-05 11:59:44
@ User089247如果这是需要,为什么不修复它来自哪里的实际来源。为什么双重工作? – 2014-11-05 12:05:42