Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
663 views
in Technique[技术] by (71.8m points)

activerecord - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...