Ruby-on-rails Model.reset_column_information 不会在 Rails 迁移中重新加载列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9115347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Model.reset_column_information does not reload columns in rails migration
提问by Iain
I'm using Rails 3.2 and have a migration that contains the code:
我正在使用 Rails 3.2 并且有一个包含代码的迁移:
add_column :users, :gift_aid, :integer, :default => 2
# reset columns
User.reset_column_information
... code here to load legacy data from sqlite3 database ...
# now create a user with the loaded column data
user = User.create( ...other cols...,
:gift_aid => migrated_gift_aid_column_data,
...other cols... )
and I get unknown attribute: gift_aidwhen running the migration. User.column_namesshows the same list before and after the call to reset_column_information.
我unknown attribute: gift_aid在运行迁移时得到了。User.column_names在调用 之前和之后显示相同的列表reset_column_information。
Oddly when I manually drop the column in mysql and re-run the migration it works as expected. Starting from the first migration again with an empty database and it doesn't work so it's something to do with running all the migrations rather than the single one.
奇怪的是,当我手动删除 mysql 中的列并重新运行迁移时,它按预期工作。再次使用空数据库从第一次迁移开始,但它不起作用,因此与运行所有迁移而不是单个迁移有关。
I have a couple of previous migrations on User model, both include reset_column_informationand both work fine.
我之前有几个关于 User 模型的迁移,都包含reset_column_information并且都可以正常工作。
I'm really scratching my head on this one - anyone got any ideas
我真的很抓狂 - 任何人都有任何想法
回答by Seamus Abshere
I think this must be some kind of bug related to schema caching... this might work:
我认为这一定是与模式缓存相关的某种错误......这可能有效:
User.connection.schema_cache.clear!
User.reset_column_information
(for Rails 3.2.2)
(对于 Rails 3.2.2)
回答by localhostdotdev
this isn't needed on rails 6 (tested on 6.0.0beta3).
这在 rails 6 上不需要(在 6.0.0beta3 上测试)。
I tried both with update!(new_column: ...)and update_all(new_column: ...)
我试过update!(new_column: ...)和update_all(new_column: ...)

