Model.reset_column_information does not reload columns in rails migration

二次信任 提交于 2019-12-17 21:56:16

问题


I'm using Rails 3.2 and have a migration that contains the code:

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_aid when running the migration. User.column_names shows the same list before and after the call to 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.

I have a couple of previous migrations on User model, both include reset_column_information and both work fine.

I'm really scratching my head on this one - anyone got any ideas


回答1:


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)




回答2:


this isn't needed on rails 6 (tested on 6.0.0beta3).

I tried both with update!(new_column: ...) and update_all(new_column: ...)



来源:https://stackoverflow.com/questions/9115347/model-reset-column-information-does-not-reload-columns-in-rails-migration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!