Rails 迁移脚本 VS 控制台
所以我试图在迁移脚本中迁移一些数据,但数据似乎没有保存。但是,如果我复制代码并直接在控制台中运行它,它确实会保存。谁能帮我弄清楚为什么?
这是我的迁移脚本中的代码。我正在将我的头像数据从它自己的表移动到我的个人资料表中。
def self.up
add_column :users, :featured, :boolean, :default => false
add_column :profiles, :avatar_file_name, :string
add_column :profiles, :avatar_content_type, :string
add_column :profiles, :avatar_file_size, :integer
add_column :profiles, :avatar_updated_at, :datetime
Avatar.all.each do |a|
user = User.find(a.user_id)
user.profile.avatar_file_name = a.avatar_file_name
user.profile.avatar_content_type = a.avatar_content_type
user.profile.avatar_file_size = a.avatar_file_size
user.profile.avatar_updated_at = a.updated_at
if a.featured == true
user.featured = true
end
user.save
end
# drop_table :avatars
end
so i am trying to migrate some data in a migration script, but the data does not seem to be saving. however, if i copy the code and run it directly in the console, it does save. can anyone help me figure out why?
this is the code from my migration script. i am moving my avatar data from its own table into my profiles table.
def self.up
add_column :users, :featured, :boolean, :default => false
add_column :profiles, :avatar_file_name, :string
add_column :profiles, :avatar_content_type, :string
add_column :profiles, :avatar_file_size, :integer
add_column :profiles, :avatar_updated_at, :datetime
Avatar.all.each do |a|
user = User.find(a.user_id)
user.profile.avatar_file_name = a.avatar_file_name
user.profile.avatar_content_type = a.avatar_content_type
user.profile.avatar_file_size = a.avatar_file_size
user.profile.avatar_updated_at = a.updated_at
if a.featured == true
user.featured = true
end
user.save
end
# drop_table :avatars
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这是因为您正在更改列并尝试在同一迁移中使用它们,但模型不了解这些字段。
尝试在 Avatar.all.each 上方添加这些行...
有关此的更多信息 http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-reset_column_information
I think it's because you're changing the columns and trying to use them in the same migration, but the model doesn't know about the fields.
Try adding these lines above Avatar.all.each...
More about this http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-reset_column_information