Skip to content

Instantly share code, notes, and snippets.

@servel333
Last active March 1, 2024 21:13
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save servel333/47f6cca9e51497aeefab to your computer and use it in GitHub Desktop.
Save servel333/47f6cca9e51497aeefab to your computer and use it in GitHub Desktop.
Rails seeds for environments
## db/seeds.rb
['all', Rails.env].each do |seed|
seed_file = Rails.root.join('db', 'seeds', "#{seed}.rb")
if File.exists?(seed_file)
puts "*** Loading #{seed} seed data"
require seed_file
end
seed_dir = Rails.root.join('db', 'seeds', seed)
if File.directory?(seed_dir)
Dir[File.join(seed_dir, "*.rb")].each do |file|
puts "*** Loading #{seed} seed data from #{file}"
require file
end
end
end
##############################
## Example of folder structure
## db/seeds/all.rb
# Seeds for all environments
## db/seeds/development.rb
# Seeds only for the "development" environment.
## db/seeds/test.rb
# Seeds only for the "test" environment.
## db/seeds/production.rb
# Seeds only for the "production" environment.
## db/seeds/development/users.rb
# Seeds only for the "development" environment.
# ... seed users ...
## db/seeds/development/articles.rb
# Seeds only for the "development" environment.
# ... seed articles ...
## db/seeds/production/users.rb
# Seeds only for the "production" environment.
# ... seed users ...
## db/seeds/production/articles.rb
# Seeds only for the "production" environment.
# ... seed articles ...
#########################################
## Recommended shared seeds files pattern
## db/seeds/shared/dev_users.rb
# Seeds for any environment but must be manually required
# ... create users only for some environments.
## db/seeds/development.rb
# Seeds only for the "development" environment.
require_relative "shared/dev_users.rb"
## db/seeds/staging.rb
# Seeds only for the "staging" environment.
require_relative "shared/dev_users.rb"
@NathanielPerryAtAwatoXello

Security consideration: If a file can be dropped into /db/seeds/production/* then the attacker can load whatever they want into your project. This would require a codebase files compromise, or a server file system compromise.

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