添加自定义种子文件 [英] Adding a custom seed file
问题描述
我想用虚拟数据填充新功能,但不想使用 db/seeds.rb 文件,因为它已经包含与此功能无关的其他数据的种子.
I want to populate a new feature with dummy data, but don't want to use the db/seeds.rb file as it already has seeds other data irrelevant for this feature.
要运行默认的 seeds.rb
文件,请运行命令 rake db:seed
.
To run the default seeds.rb
file, you run the command rake db:seed
.
如果我在 db
目录中创建一个名为 seeds_feature_x.rb
的文件,那么 rake 命令会如何(仅)运行该文件?
If I create a file in the db
directory called seeds_feature_x.rb
, what would the rake command look like to run (only) that file?
推荐答案
首先创建一个单独的目录来保存您的自定义种子 - 此示例使用 db/seeds
.然后,通过将 rakefile 添加到您的 lib/tasks
目录来创建自定义任务:
Start by creating a separate directory to hold your custom seeds – this example uses db/seeds
. Then, create a custom task by adding a rakefile to your lib/tasks
directory:
# lib/tasks/custom_seed.rake
namespace :db do
namespace :seed do
Dir[Rails.root.join('db', 'seeds', '*.rb')].each do |filename|
task_name = File.basename(filename, '.rb')
desc "Seed " + task_name + ", based on the file with the same name in `db/seeds/*.rb`"
task task_name.to_sym => :environment do
load(filename) if File.exist?(filename)
end
end
end
end
此 rakefile 接受 db/seeds
目录中的种子文件的名称(不包括 .rb
扩展名),然后像运行 一样运行它种子.rb
.您可以通过从命令行发出以下命令来执行 rake 任务:
This rakefile accepts the name of a seed file in the db/seeds
directory (excluding the .rb
extension), then runs it as it would run seeds.rb
. You can execute the rake task by issuing the following from the command line:
rake db:seed:file_name # Name of the file EXCLUDING the .rb extension
更新:现在它也应该在运行 rake --tasks
或 rake -T
时列出种子任务.
Update: Now it should also list the seed tasks when running rake --tasks
or rake -T
.
这篇关于添加自定义种子文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!