Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split seeds.rb into multiple sections?

I'd like to split my seeds.rb file into multiple sections for ease of maintenance; seed all the A's in a.rb, the B's in b.rb, etc. The separate files are located in the db/ directory with seeds.rb. Each file consists of a bunch of "A.create" or "B.create" calls and I want to call those files from seeds.rb.

I've tried:

include 'a'
include 'b'

and

load 'a.rb'
load 'b.rb' 

in my seeds.rb but they don't seem to be processed when I call "rake db:seed". This is probably more of a straight ruby question than a rails question but for completeness I'm using Ruby 1.9.2 and Rails 3 on a Mac.

like image 832
GSP Avatar asked Dec 26 '10 05:12

GSP


People also ask

What is db seeds rb?

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. rake db:setup.

Why we use seeding in rails?

What is Seed in Rails ? A useful way of populating a database with the initial data needed for a Rails project. This will allow us to populate the database in within our Rails Web application.

How do you use seeds in rails?

When the database is not ready yet, in other words, we want to create the database first, then we can go with rails db:setup to first run migrations and then seeding. And the last option is when we want to reset the database, rails db:reset will drop the database, create again, and seed the application.


1 Answers

In ./db/seeds/my_module.rb:

module MyModule
  puts "In my_module.rb"
  # add code here
end

In ./db/seeds.rb:

require File.expand_path('../seeds/my_module', __FILE__) # the ../ just removes `seeds.rb` filename from the path which is given by __FILE__

p "In seeds.rb"
# add code here
like image 193
Zabba Avatar answered Sep 20 '22 18:09

Zabba