可以使用Rails迁移来转换数据吗? [英] Can Rails Migrations be used to convert data?
问题描述
我正在尝试在Rails应用程序中转换列,出于参数考虑,让我们假装我正在尝试将users
表中的age
列更改为字符串表示形式,而不是整数.
I'm trying to convert a column in my Rails app, for arguments sake let's pretend I'm trying to change the age
column in my users
table to a string representation rather than an int.
在我的迁移中,我有这个;
In my migration I have this;
def.self up
add_column :users, :age_text, :string
users = User.find(:all)
users.each do |u|
u.age_text = convert_to_text(u.age)
u.save
end
end
def self.convert_to_text(number)
#code here to convert 1 to 'one' etc
end
但是它似乎没有用,我在这里尝试甚至可以进行迁移吗?
But it doesn't seem to be working, is what I'm attempting here even possible with migrations?
推荐答案
您正在尝试做的事情是可能的,我会说正确的事情.
What you're trying to do is possible, and I would say the correct thing to do.
但是,您需要为迁移中要更新的模型类重新加载列信息,以便Rails知道新列.试试这个:
You need, though, to reload the column info for the model classes you're updating in the migration, so that Rails knows about the new columns. Try this:
def.self up
add_column :users, :age_text, :string
User.reset_column_information
users = User.find(:all)
users.each do |u|
u.age_text = convert_to_text(u.age)
u.save
end
end
另外,请注意,如果您的桌子很大,那么一一进行更新将需要很长的时间..请注意这一点.
On a separate note, please note that if your table is large, doing updates one by one will take a looong time.. Be careful with that.
这篇关于可以使用Rails迁移来转换数据吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!