'railsgigs.com' domain name for sale (€ 2000). Contact me for details.

Rails fixtures blues

2008-10-27 21:44 UTC

I just lost five minutes because of ‘rake db:fixtures:load’ throwing an error. Here are my top fixtures woes in the hope it benefits others:

  • It borks if one of your models is accidentally using the plural form (e.g. posts) instead of the singular form (post). It more than once happened to me that I quickly created some models (posts[sic], comment, image), proceeded to create some fixtures and then stared at a nondescript error thrown by ‘fixtures:load’. I must confess that this only happens to me when I create models and fixtures by hand (instead of relying on script/generate).
  • It stumbles if you accidentally typed e.g. ‘belongs_to :User’ instead of using all lowercase. Again, stupid, but it happens, certainly when copying/pasting a class name behind ‘belongs_to’.
  • Don’t use the ‘_id’ suffix when using fixture names to reference foreign keys. So it’s either ‘user_id: 1’ or ‘user: jack’ but not ‘user_id: jack’. You can easily be bitten by this when cleaning up fixtures in older projects. Usually I check the loaded fixture data to see if everything has fallen into place. You can do a manual check using the Rails script/console.
  • This one is particularly nasty: never leave some half-baked work-in-progress code in a model when loading fixtures. The reason is, of course, that ‘fixtures:load’ needs to load each model class it references when executing the fixtures. However the error it throws with broken model code is something like ‘Unknown column ’foo’ in ‘field list’…‘. Not an error that really tells ’hey dude, your model code is broken, fix it and run me again’. You can test this behavior by entering ‘foo’ between two method declarations in a model and running ‘fixtures:load’.

One more thing about fixtures, there’s an easy way to preload your production database with all your fixture data: ‘rake db:fixtures:load RAILS_ENV=production’. The RAILS_ENV part tells the ‘fixtures:load’ command to use the production database settings instead of the development credentials which it uses by default.

0 comments

Leave a reply

Name (required)
Mail (optional, will not be published)
Website (optional)
Anti-spam question: What is the sum of 4 and 6?