26

How can one make the task rake db:seed to use different seeds.rb file on production and development?

edit: any better strategy will be welcome

masterweily
  • 736
  • 1
  • 7
  • 15
  • 2
    take a look here: http://stackoverflow.com/questions/8662127/how-to-use-seed-rb-to-selectively-populate-development-and-or-production-databas – flyingjamus May 29 '13 at 08:17

2 Answers2

59

You can have a rake task behave differently based on the current environment, and you can change the environment a task runs in by passing RAILS_ENV=production to the command. Using these two together you could produce something like so:

Create the following files with your environment specific seeds:

db/seeds/development.rb
db/seeds/test.rb
db/seeds/production.rb

Place this line in your base seeds file to run the desired file

load(Rails.root.join( 'db', 'seeds', "#{Rails.env.downcase}.rb"))

Call the seeds task:

rake db:seed RAILS_ENV=production 
Matt
  • 13,948
  • 6
  • 44
  • 68
  • Is this still the preferable technique for Rails 4? – Donato Apr 06 '15 at 16:22
  • 4
    I don't know if it is the preferable technique. But it sure as hell works perfectly. – rryter Jan 28 '16 at 15:19
  • 1
    Just what I was looking for. I made some other custom environments like ci and qa too. Just be sure those others are also defined in database.yml and in the config/environments folder. – ed209 Feb 03 '16 at 02:31
  • Hey! If you want something a bit more detailed, I've written this example up as an article on my blog — [Split your database seeds.rb by Rails environment | RailsNotes](https://railsnotes.xyz/blog/split-seeds-rb-by-rails-environment) – Harrison Broadbent Jul 31 '23 at 07:26
10

I like to implement all seeds inside one seed.rb file and then just separate the environments inside.

if Rails.env.production? 
  State.create(state: "California", state_abbr: "CA")
  State.create(state: "North Dakota", state_abbr: "ND")
end

if Rails.env.development?
  for 1..25
    Orders.create(order_num: Faker::Number:number(8), order_date: Faker::Business.credit_card_expiry_date)
  end
end

That way you do not need to cast the RAILS_ENV property on your rake task, or manage multiple files. You also can include Rails.env.test?, but I personally let RSPEC take care of the testing data.

Beengie
  • 1,588
  • 4
  • 18
  • 36