开发者

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.开发者_StackOverflow中文版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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜