Reputation: 366
I have a Rails 6 application used in production. When I upgrade my app, I add migrations for new tables and/or columns.
What is the best way if I have to add new default datas ?
I use seed file for initial datas, but is there something like migrations (incremental) to add datas ? I know I can add datas in migrations but I would prefer another place for that.
[EDIT] Do someone know this gem : https://github.com/ilyakatz/data-migrate ? It seems to do what I am looking for.
Upvotes: 0
Views: 243
Reputation: 366
If someone is looking for a simple solution, data_migrate does exactly what I wanted.
https://github.com/ilyakatz/data-migrate
Data migrations are stored in db/data. Data migrations are included in schema migration workflow with simple commands as :
rails db:migrate:with_data
If you can read spanish, this is an interesting documentation on data_migrate : https://la-guia.platan.us/stack/ruby/rails/data_migrate
When it is possible, you should avoid using ActiveRecord models in data migrations. Models are subject to change and if, for example, you have added validations it is possible that your data migrations will not pass.
This is well explained here : https://medium.com/@jeffcoh23/why-you-should-avoid-activerecord-when-using-ruby-on-rails-data-migrate-gem-2651739395d9
A good solution is to call a model created just for data migration :
class AddVisitorRoleToUsers < ActiveRecord::Migration[6.0]
class MigrationUser < ApplicationRecord
self.table_name = :users
end
def up
MigrationUser.all.each do |user|
user.update!(role: 'visitor')
# This will NOT call User model validations
end
end
def down
raise ActiveRecord::IrreversibleMigration
end
end
Upvotes: 1
Reputation: 64
In some projects we use to put data updates into db/data-updates/<UTC TimeStamp>_add_thing.rb
. We created an own generator for those, called by rails generate data_update AddThing
to create a migration calling / executing the contents from the corresponding update file.
Based on that you can put those default datas into db/default-data
with similar logic for your new defaults.
You don't need to call them by mirgrations, you also may run them as rails runner db/default-data/123_xyz.rb
in your differnt environments.
But if the new defaults are mandatory for your busines logic you should keep them as close as possible to the inventing migration!
Upvotes: 1