Split seeds.rb into multiple sections?

我是研究僧i 提交于 2019-11-29 18:09:29

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/4532834/split-seeds-rb-into-multiple-sections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!