Adding a custom seed file

后端 未结 3 1741
没有蜡笔的小新
没有蜡笔的小新 2020-12-12 12:44

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.

To run

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-12 12:53

    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
    

    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 
    

    Update: Now it should also list the seed tasks when running rake --tasks or rake -T.

提交回复
热议问题