将 seeds.rb 分成多个部分?

发布于 2024-10-09 04:08:19 字数 405 浏览 2 评论 0原文

我想将 seeds.rb 文件分成多个部分以便于维护;将所有 A 种子放入 a.rb 中,将 B 种子放入 b.rb 中,等等。单独的文件位于 db/ 目录中,包含 seeds.rb。每个文件都包含一堆“A.create”或“B.create”调用,我想从 seeds.rb 调用这些文件。

我已经尝试过:

include 'a'
include 'b'

在我的 seeds.rb 中,

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

但当我调用“rake db:seed”时它们似乎没有被处理。这可能更像是一个直接的 Ruby 问题,而不是 Rails 问题,但为了完整起见,我在 Mac 上使用 Ruby 1.9.2 和 Rails 3。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

旧时浪漫 2024-10-16 04:08:19

在 ./db/seeds/my_module.rb 中:

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

在 ./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

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
楠木可依 2024-10-16 04:08:19

我建议创建一个新的 db/seeds/ 目录,您可以在其中放置各种种子文件:

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

然后编辑您的 db/seeds.rb 文件

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

:甚至可以按照您喜欢的顺序加载种子 - 这通常是要求的。


此解决方案最初由 nathanvda 在这个“重复”问题中提出。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文