11

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.

GSP
  • 3,763
  • 3
  • 32
  • 54

2 Answers2

20

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
Magne
  • 16,401
  • 10
  • 68
  • 88
Zabba
  • 64,285
  • 47
  • 179
  • 207
  • 9
    I'm not sure if putting them in `db/migrate` is a great idea; migrations and seeds are different and should be treated as such. Instead, a `db/seed` directory would probably be better. – vonconrad Dec 26 '10 at 07:41
  • 3
    Yes, please don't put these in `db/migrate`, they belong in a separate folder such as `db/seed`. – Ryan Bigg Dec 26 '10 at 08:03
  • Worked like a charm, of course. Thank! (And, I put them in a separate "seeds" directory) – GSP Dec 27 '10 at 22:21
4

I would propose to create a new db/seeds/ directory where you can place your various seeds file:

db/seeds/01_stuff_that_comes_for_first.rb
db/seeds/02_stuff_that_comes_for_second.rb
...

And then edit your db/seeds.rb file with:

Dir[File.join(Rails.root, 'db', 'seeds', '*.rb')].sort.each { |seed| load seed }

So, you can load your seeds even in the order you prefer - that is often something requested.


This solution was originally proposed by nathanvda in this "duplicated" question.

Community
  • 1
  • 1
damoiser
  • 6,058
  • 3
  • 40
  • 66