# Seed Dump Seed Dump is a Rails plugin (compatible with **Rails 4 through 8+**) that adds a rake task named `db:seed:dump`. It allows you to create seed data files from the existing data in your database. You can also use Seed Dump from the Rails console. See below for usage examples. Note: if you want to use Seed Dump with Rails 3 or earlier, use [version 0.5.3](http://rubygems.org/gems/seed_dump/versions/0.5.3). ## Installation Add it to your Gemfile with: ```ruby gem 'seed_dump' ``` Or install it by hand: ```sh $ gem install seed_dump ``` ## Examples ### Rake task Dump all data directly to `db/seeds.rb`: ```sh $ rake db:seed:dump ``` Result: ```ruby Product.create!([ { category_id: 1, description: "Long Sleeve Shirt", name: "Long Sleeve Shirt" }, { category_id: 3, description: "Plain White Tee Shirt", name: "Plain T-Shirt" } ]) User.create!([ { password: "123456", username: "test_1" }, { password: "234567", username: "test_2" } ]) ``` Dump only data from the users table and dump a maximum of 1 record: ```sh $ rake db:seed:dump MODELS=User LIMIT=1 ``` Result: ```ruby User.create!([ { password: "123456", username: "test_1" } ]) ``` Append to `db/seeds.rb` instead of overwriting it: ```sh rake db:seed:dump APPEND=true ``` Use another output file instead of `db/seeds.rb`: ```sh rake db:seed:dump FILE=db/seeds/users.rb ``` Exclude `name` and `age` from the dump: ```sh rake db:seed:dump EXCLUDE=name,age ``` There are more options that can be set— see below for all of them. ### Console Output a dump of all User records: ```ruby irb(main):001:0> puts SeedDump.dump(User) User.create!([ { password: "123456", username: "test_1" }, { password: "234567", username: "test_2" } ]) ``` Write the dump to a file: ```ruby irb(main):002:0> SeedDump.dump(User, file: 'db/seeds.rb') ``` Append the dump to a file: ```ruby irb(main):003:0> SeedDump.dump(User, file: 'db/seeds.rb', append: true) ``` Exclude `name` and `age` from the dump: ```ruby irb(main):004:0> SeedDump.dump(User, exclude: [:name, :age]) ``` Options are specified as a Hash for the second argument. In the console, any relation of ActiveRecord rows can be dumped (not individual objects though): ```ruby irb(main):005:0> puts SeedDump.dump(User.where(is_admin: false)) User.create!([ { password: "123456", username: "test_1", is_admin: false }, { password: "234567", username: "test_2", is_admin: false } ]) ``` ## Options Options are common to both the Rake task and the console, except where noted. `append`: If set to `true`, append the data to the file instead of overwriting it. Default: `false`. `batch_size`: Controls the number of records that are processed and written at a given time. Default: 1000. If you're running out of memory when dumping, try decreasing this. If things are dumping too slow, trying increasing this. `exclude`: Attributes to be excluded from the dump. Pass a comma-separated list to the Rake task (e.g., `EXCLUDE=name,age`) and an array of symbols on the console (e.g., `exclude: [:name, :age]`). Default: `[:id, :created_at, :updated_at, :created_on, :updated_on]`. `file`: Write to the specified output file. The Rake task default is `db/seeds.rb`. The console returns the dump as a string by default if this option is omitted. `group_sti_by_class`: If `true`, Single Table Inheritance (STI) records are grouped by their actual class (e.g., `Dog`, `Cat`) instead of the base class (e.g., `Animal`). This is necessary when STI subclasses have different enum definitions or other class-specific attributes that would be lost if dumped via the base class. Default: `false`. Example: `rake db:seed:dump GROUP_STI_BY_CLASS=true` or `SeedDump.dump(Animal, group_sti_by_class: true)`. See the STI Handling section below for more details. `header`: If `true`, adds a comment header to the output file showing the seed_dump command and options used. If a string, uses that string as the header comment. Default: `false`. **Rake task only.** Example: `rake db:seed:dump HEADER=true` or `HEADER="Generated by seed_dump"`. `import`: If `true`, output will be in the format needed by the [activerecord-import](https://github.com/zdennis/activerecord-import) gem, rather than the default format. You can also pass a Hash of options which will be passed through to the `import` call (e.g., `IMPORT='{ "validate": false }'` for Rake, or `import: { validate: false }` for console). Default: `false`. `include_all`: If set to `true`, include all columns in the dump (including `id`, `created_at`, and `updated_at`). Equivalent to `EXCLUDE=""`. Default: `false`. **Rake task only.** Example: `rake db:seed:dump INCLUDE_ALL=true` `insert_all`: If `true`, output will use Rails 6+ [`insert_all`](https://api.rubyonrails.org/classes/ActiveRecord/Persistence/ClassMethods.html#method-i-insert_all) for faster bulk inserts that bypass validations and callbacks. Default: `false`. Example: `rake db:seed:dump INSERT_ALL=true` or `SeedDump.dump(User, insert_all: true)`. `limit`: Dump no more than this amount of data *per model*. Default: no limit. **Rake task only.** In the console, just pass in an ActiveRecord::Relation with the appropriate limit (e.g., `SeedDump.dump(User.limit(5))`). `model_limits`: Set different limits for specific models. Format: `Model1:limit1,Model2:limit2`. Use `0` to mean "no limit" for a specific model. This is useful when `LIMIT` would break foreign key relationships. **Rake task only.** Example: `rake db:seed:dump LIMIT=10 MODEL_LIMITS="Teacher:0,Student:50"` dumps all Teachers, 50 Students, and 10 of everything else. `model[s]`: Restrict the dump to the specified comma-separated list of models. Default: all models that have data. If you are using a Rails engine you can dump a specific model by passing "EngineName::ModelName". **Rake task only.** Example: `rake db:seed:dump MODELS="User, Position, Function"` `models_exclude`: Exclude the specified comma-separated list of models from the dump. Default: no models excluded. **Rake task only.** Example: `rake db:seed:dump MODELS_EXCLUDE="User"` `upsert_all`: If `true`, output will use Rails 6+ [`upsert_all`](https://api.rubyonrails.org/classes/ActiveRecord/Persistence/ClassMethods.html#method-i-upsert_all) which preserves record IDs and handles conflicts by updating existing records. This is useful when you need to maintain foreign key relationships or want idempotent seed files. Automatically includes `id` in the dump. Default: `false`. Example: `rake db:seed:dump UPSERT_ALL=true` or `SeedDump.dump(User, upsert_all: true)`. ## Automatic Behaviors **Foreign Key Ordering**: Models are automatically dumped in dependency order based on foreign key relationships. This ensures that parent records are created before child records that reference them. **STI Handling**: Single Table Inheritance (STI) models are automatically deduplicated. By default, only the base class is dumped to avoid duplicate records (e.g., `Animal.create!` for both `Dog` and `Cat` records). However, if your STI subclasses have different enum definitions or other class-specific attributes, use the `group_sti_by_class: true` option to dump each subclass separately (e.g., `Dog.create!` and `Cat.create!`). This ensures that subclass-specific type casting and validations are properly applied when the seed data is loaded. **HABTM Handling**: Has-and-belongs-to-many join tables are automatically detected and dumped without duplication. ## Usage Outside of Rails If you're using ActiveRecord outside of Rails (e.g., with [standalone-migrations](https://github.com/thuss/standalone-migrations)), you can set up a custom Rake task: ```ruby # In your Rakefile $LOAD_PATH.unshift(File.expand_path('app/models', __dir__)) Dir.glob(File.expand_path('app/models/*.rb', __dir__)).sort.each(&method(:require)) require 'seed_dump' namespace :db do namespace :seed do desc "Dump records from the database into db/seeds.rb" task :dump => :environment do SeedDump.dump_using_environment(ENV) end end end ``` This loads your models and creates a `db:seed:dump` task that works like the Rails version.