Skip to content

Instantly share code, notes, and snippets.

@koffeinfrei
Last active December 23, 2023 03:43
Show Gist options
  • Save koffeinfrei/04bbe38f16ff9d49bebd to your computer and use it in GitHub Desktop.
Save koffeinfrei/04bbe38f16ff9d49bebd to your computer and use it in GitHub Desktop.
Idempotent seed helper for rails -> THIS IS NOW A GEM https://github.com/panter/seed_box

Idempotent seed helper for rails

  • The first model argument is the model class
  • The second argument find_or_create_by is a hash of attributes that are used for finding a record. If the record doesn't exist, it will be created. This hash is like the unique identifier of a seed record.
  • The third argument update_with is a hash of attributes that will be always set on the record, whether the record already exists or has to be created. This is useful when the seeds are extended and you want to update existing records with new attributes.

Example usage

seed User, { email: '[email protected]' }, {
  password: 'asdfasdf',
  roles: [:admin],
  first_name: 'John',
  last_name: 'Doe'
}
# put this file in lib/tasks/db.rake
namespace :db do
# Define a helper to create or update seed records
task seed: :seed_helper
task :seed_helper do
def seed(model, find_or_create_by, update_with = {})
record = model.where(find_or_create_by).first_or_initialize
if record.update_attributes(update_with)
record
else
raise "Couldn't save #{record.class} (#{record.errors.full_messages.join(', ')})"
end
end
end
end
# put this file in db/seeds.rb
seed User, { email: '[email protected]' }, {
password: 'asdfasdf',
roles: [:admin],
first_name: 'John',
last_name: 'Doe'
}
@veryeasily
Copy link

This is great! thanks

@koffeinfrei
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment