user3309314
user3309314

Reputation: 2543

Rails db:seed unknown attribute

Here is a question.

I have an Rails project. When I want to clear my database and fill it with some test data I run:

rake db:drop db:create db:migrate db:seed

and I have an error:

NoMethodError: undefined method login for #<User:0x007fecf46afe80>

When I run separately:

rake db:drop db:create db:migrate
rake db:seed

all goes fine.

Also all my actions in db/seeds.rb are wrapped in ActiveRecord::Base.transaction block.

I had to add User.reset_column_information in the top of my db/seeds.rb to make

rake db:drop db:create db:migrate db:seed

working.

I didn't have the same errors before without reset_column_information. Does somebody have any ideas why it's happen?

PS: after running rake db:drop db:create db:migrate there is "missing" column in db/schema.rb and I can see this column in DB directly

Upvotes: 4

Views: 1656

Answers (1)

Toby 1 Kenobi
Toby 1 Kenobi

Reputation: 5037

From the docs:

reset_column_information() public

Resets all the cached information about columns, which will cause them to be reloaded on the next request.

The most common usage pattern for this method is probably in a migration, when just after creating a table you want to populate it with some default values

You're db:migrate task changes the column information in the users table, but it looks like these changes are not properly written to the db/schema.rb file until the rake cammand finishes. Your db:seed task looks at db/schema.rb to see if the columns it needs exists, but this shows the schema as it was before the db:migrate unless you put it in a separate rake command or you run reset_column_information() before it.

Upvotes: 5

Related Questions