Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model.reset_column_information does not reload columns in rails migration

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

like image 524
Iain Avatar asked Feb 02 '12 15:02

Iain


People also ask

How do I redo a migration in Rails?

You must rollback the migration (for example with bin/rails db:rollback ), edit your migration, and then run bin/rails db:migrate to run the corrected version.

How can I check my Rails migration status?

If you need a bash one-liner to determine whether to run a migration or not (e.g., only migrate in a Heroku release phase command when there is a pending migration), this works: (rails db:migrate:status | grep "^\s*down") && rails db:migrate || echo "No pending migrations found."

Can you edit a migration file Rails?

If you have already run the migration then you cannot just edit the migration and run the migration again: Rails thinks it has already run the migration and so will do nothing when you run rake db:migrate.


1 Answers

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)

like image 158
Seamus Abshere Avatar answered Sep 18 '22 11:09

Seamus Abshere