Seeding databases using more complex Rails fixtures

Apr 25, 2016

Ruby on Rails applications can be easily tested using fixtures to load the initial data. Each fixture filename would normally match the model name, and any exception to that rule would use the set_fixture_class method to map the
fixture and the model.

The set_fixture_class solution works fine for testings, but it fails when seeding databases with rails db:fixtures:load (a.k.a rake db:fixtures:load). The mapping created by the method is only available to tests because it is defined directly into the tests Ruby code. Therefore the db:fixtures:load task cannot use it to load the fixtures.

A solution has recently been introduced to the Rails 5 and will allow the mapping to be done from the fixture file itself. The following case loads the User model from the accounts table:

Using the model_class property from _fixture in the YAML file, the accounts fixtures can now instantiate User records:

# accounts.yml_fixture:model_class:Useradmin:name:'Foo'

That allows db:fixtures:load to recognize the model and to seed the records. The setting is also transparent to the model associations. So if there is a scenario where a user can have many roles, it can be described in the roles fixture without any mention to accounts: