Model.reset_column_information does not reload columns in rails migration
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)
Iain
Updated on July 09, 2022Comments
-
Iain almost 2 years
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 toreset_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
-
Iain about 12 yearsI think you may be right. I actually had two calls to
User.reset_column_information
in two different migrations and it was the second one that was failing. I fixed it by reorganising my migrations so I only had one call toreset_column_information
(because I have yet to finally deploy the site so it's no problem going back). This solution looks like it could work too. I'll test it if I get a chance. -
Iain about 12 yearsI can confirm this does the job just fine. Looks like with long migrations and multiple changes to a model only the first
reset_column_information
works. Clearing the schema cache makes it work just fine! Thanks :) -
hrdwdmrbl almost 11 yearsThank you so much! This was driving me badshit since the Rails docs clearly write something different -> guides.rubyonrails.org/…
-
stevenspiel over 8 yearsis there an option for Rails 2?
-
Fumisky Wells over 8 yearsI saw the same issue in Rails 3.2.22 and fixed by this workaround, thanks you!
-
Toshihiro Yokota almost 4 yearsAnyone knows how about on Rails5?
-
ELI7VH over 3 yearsthis problem persists for me on rails 6
-
Iain over 3 yearsYes it does seem to still be there. As the original poster (all those years ago) I just ran into it on a new project using Rails 6. The work around still appears to work though so that's at leats something.
-
Joshua Pinter almost 3 yearsDid the trick for us on Rails 5.2. Thanks.
-
Joshua Pinter almost 3 years@ToshihiroYokota This was an issue for us on Rails 5.2 and needed to use the accepted answer to work around it:
User.connection.schema_cache.clear! User.reset_column_information
-
Iain almost 2 yearsAnd still today in Rails 7...