Rails不允许我在迁移过程中更改记录 [英] Rails won't let me change records during migration

查看:50
本文介绍了Rails不允许我在迁移过程中更改记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这一定是简单的事情,但这让我发疯了!
我有一个迁移,我想在以后更新记录

This must be something simple but it's driving me nuts!
I have a migration where I want to update a record afterward

class SubjectsTextField < ActiveRecord::Migration
  def self.up
    add_column :users, :subjects, :text

    User.find(39).update_attribute :subjects, "hey there"
  end

  def self.down
    remove_column :users, :subjects
  end
end

该列已创建,但是当我检查记录39时,它的subject字段为空,并且不说嘿".在迁移过程中不会引发任何错误,并且update_attribute行返回true就像工作一样.

The column gets created but when I go to check record 39, it's subjects field is null and doesn't say "hey there". No errors are thrown during the migration and the update_attribute line returns true as if it had worked.

此行可在控制台中完美运行,并具有预期的效果:

This line works perfectly in the console and has the expected effect:

User.find(39).update_attribute :subjects, "hey there"

我尝试将update_attribute行放入第二个迁移中.如果我以一个"rake db:migrate"一路吹打它们直到目前,都仍然无法正常工作.

I tried putting the update_attribute line in a second migration. If I blow through both of them in one "rake db:migrate" all the way to current, it still doesn't work.

但这是奇怪的部分.如果我运行两个单独的迁移,请说"rake db:migrate VERSION = 10"仅创建该列,然后说第二个带有"rake db:migrate"的列以更新属性IT WORKS!

But here is the weird part. If I run two separate migrations, say "rake db:migrate VERSION=10" to only create the column and then the second one with "rake db:migrate" to update the attribute IT WORKS!

到底发生了什么...在迁移期间如何修改记录?我似乎记得过去经常这样做.也许与Rails 2.3.2有所不同?

What the heck is going on...how do I modify a record during a migration? I seem to remember doing this quite often in the past. Maybe it is something different with Rails 2.3.2?

谢谢! 布莱恩

推荐答案

您需要在更改的模型上调用reset_column_information,然后才能使用新列.将其添加到add_column和更新之间:

You need to call reset_column_information on the model you changed before you can use the new column. Add this between the add_column and update:

User.reset_column_information

参见 ActiveRecord :: Migration 页面.

这篇关于Rails不允许我在迁移过程中更改记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆