Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby On Rails: way to create different seeds file for environments

Tags:

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

like image 843
masterweily Avatar asked May 29 '13 08:05

masterweily


People also ask

How do I run a specific seed in rails?

To run the default seeds. rb file, you run the command rake db:seed . If I create a file in the db directory called seeds_feature_x. rb , what would the rake command look like to run (only) that file?

What is seed file in rails?

Rails seed files are a useful way of populating a database with the initial data needed for a Rails project. The Rails db/seeds. rb file contains plain Ruby code and can be run with the Rails-default rails db:seed task.

What is seed rb file?

The seeds.rb file is where the seed data is stored, but you need to run the appropriate rake task to actually use the seed data. Using rake -T in your project directory shows information about following tasks: rake db:seed. Load the seed data from db/seeds.rb.


2 Answers

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  
like image 96
Matt Avatar answered Sep 28 '22 06:09

Matt


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.

like image 20
Beengie Avatar answered Sep 28 '22 05:09

Beengie