How to use seed.rb to selectively populate development and/or production databases?

Ruby on-RailsRuby on-Rails-3Environment

Ruby on-Rails Problem Overview


I am using seed.rb to populate both my development and production database. I usually populate the first with dummy data and the latter with the real minimal data that my app needs to run (e.g. the first user and so on).

How can I specify in seed.rb for what environment each data is?

Given that I know "group" to be a Gemfile method, I'd like to achieve the same behavior for seed.rb.

E.g. I'd like to write something like this in my seed.rb:

group :development do 
  # development specific seeding code
end

group :production do 
  # production specific seeding code
end

# non-specific seeding code (it always runs) 

This to be able to call both the development-specific and the non-specific code with

$ rake db:seed

And to call both the production-specific and the non-specific code with:

$ rake db:seed RAILS_ENV=production 

Thank you

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

seeds.rb is just a plain ruby file, so there are several ways you could approach this. How about a case statement?

# do common stuff here

case Rails.env
when "development"
   ...
when "production"
   ...
end

Solution 2 - Ruby on-Rails

Another approach could be creating:

db/seeds/development.rb
db/seeds/production.rb
db/seeds/any_other_environment.rb

Then in db/seeds.rb:

# Code you want to run in all environments HERE
# ...
load(Rails.root.join( 'db', 'seeds', "#{Rails.env.downcase}.rb"))

Then write the code you want to run for each environment in the respective file.

Solution 3 - Ruby on-Rails

another approach, quite similar to @fabro's answer: add a folder seeds to db/ with the environment names and another named common.rb, so you get something like:

db/seeds/common.rb
db/seeds/development.rb
db/seeds/staging.rb
db/seeds/production.rb

than, in your seed.rb:

ActiveRecord::Base.transaction do
  ['common', Rails.env].each do |seedfile|
    seed_file = "#{Rails.root}/db/seeds/#{seedfile}.rb"
    if File.exists?(seed_file)
      puts "- - Seeding data from file: #{seedfile}"
      require seed_file
    end
  end
end

I perfer running the seed in one transaction

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDarmeView Question on Stackoverflow
Solution 1 - Ruby on-RailscamView Answer on Stackoverflow
Solution 2 - Ruby on-RailsfabroView Answer on Stackoverflow
Solution 3 - Ruby on-RailsyossicoView Answer on Stackoverflow