Reputation: 9895
In my application, I have users and roles. Some of the roles should always exist, such as "Admin". Where should I do something like:
Role.create(name: 'Admin')
In the past, I've always placed these lines in a migration to ensure it ends up on the deployed server. This sometimes leads to issues as a developer may forget to instead write it like:
Role.where(name: 'Admin').first_or_create
Should they go in the seeds.rb
file? I have generally used the seeds file for local development "playing around" data.
What is the Rails Best Practice for generating static data?
Upvotes: 0
Views: 302
Reputation: 96
Rails way is to use seeds.rb
- simple and useful.
In my opinion, data migrations are needed only in situations when you must add data to existing records (after inserting new column with default value, for example)
Upvotes: 1
Reputation: 14900
The seed.rb
is the perfect place for that. Migrations are not meant to be used for anything other than convenience during development and should never be relied upon for really anything.
From the docs:
To add initial data after a database is created, Rails has a built-in 'seeds' feature that makes the process quick and easy. This is especially useful when reloading the database frequently in development and test environments. It's easy to get started with this feature: just fill up db/seeds.rb with some Ruby code, and run rails db:seed
http://edgeguides.rubyonrails.org/active_record_migrations.html#migrations-and-seed-data
Upvotes: 1