英文:
How to encrypt existing data with Ruby on Rails?
问题
我想对数据库中的某些表的某些字段进行加密。如果我在模型类中添加encrypts:'field_name'
,它不会加密已经添加到数据库中的数据。我猜我需要编写一个迁移来完成这个任务。我应该使用哪些方法或Rails模块?我在Rails指南的加密部分中没有找到相关信息。谢谢。
我尝试阅读了Rails指南和文档,但没有找到相关帮助。
英文:
I want to encrypt some fields of some tables from my db. If I add encrypts :'field_name'
to model class, it won't encrypt data already added to db. I guess I have to write a migration that will do this. What methods or Rails modules should I use? I couldn't find it in Encryption in Rails Guide.
Thank you.
I've tried to read Rails Guides and documentation, but it didn't help.
答案1
得分: 4
在你的模型数据库表中添加一个新列,并配置你的模型对该新列进行加密。
# 在迁移文件中
add_column :model_name, :attribute_name_new, :string
# 在模型中
encrypts :attribute_name_new
设置完成后,将数据从旧列复制到新的加密列中:
# 在 Rake 任务中或者直接在 Rails 控制台中执行:
ModelName.find_each do |record|
record.update(attribute_name_new: record.attribute_name)
end
最后一步是删除旧列并将新列重命名为原始属性名:
# 在迁移文件中
remove_column :model_name, :attribute_name
rename_column :model_name, :attribute_name_new, :attribute_name
根据数据库表的大小以及在运行这些步骤时是否可以接受短暂的停机时间,你可能需要或不需要对模型进行其他更改,以便在较长的时间内保持两个列的同步。
英文:
Add a new column to your model's database table and configure your model to encrypt that new column.
# in a migration
add_column :model_name, :attribute_name_new, :string
# in the model
encrypts :attribute_name_new
Once that is set up, copy the data over from the legacy column to the new encrypted column:
# in a Rake task or simply in the Rails console:
ModelName.find_each do |record|
record.update(attribute_name_new: record.attribute_name)
end
And as a last step, delete the old column and rename the new column to the original attribute name.
# in a migration
remove_column :model_name, :attribute_name
rename_column :model_name, :attribute_name_new, :attribute_name
Depending on the size of your database table and if a short downtime while running these steps is okay, you might need or not need additional changes to your model to keep both columns in sync for a longer period of time.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论