• Stars
    star
    374
  • Rank 114,346 (Top 3 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 10 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Seed Migration

Build Status Gem Version Code Climate Test Coverage

SeedMigration

Seed Migrations are a way to manage changes to seed data in a rails app in a similar way to how schema migrations are handled.

Intro

A data migration library, similar to rails built-in schema migration. It also auto generates a db/seeds.rb file, similar to how schema migrations generate the db/schema.rb file. Using this auto generated seed file makes it quick and easy to setup new environments, usually development or test.

Installation

Add gem 'seed_migration' to your Gemfile:

gem 'seed_migration'

Usage

Install and run the internal migrations

rake seed_migration:install:migrations
rake db:migrate

That will create the table to keep track of data migrations.

Generate a new migration

You can use the generator :

rails g seed_migration AddFoo

A new file will be created under db/data/ using rails migration convention:

db/data/20140407162007_add_foo.rb

You'll need to implement the #up method and if you need to be able to rollback, the #down method.

Running the migrations

To run all pending migrations, simply use

rake seed:migrate

If needed, you can run a specific migration:

rake seed:migrate MIGRATION=20140407162007_add_foo.rb

Rollback

Rolling back the last migration is as simple as:

rake seed:rollback

You can rollback more than one migration at the same time:

rake seed:rollback STEP=3 # rollback last 3 migrations

Or rollback a specific migration:

rake seed:rollback MIGRATION=20140407162007_add_foo.rb

Status

See the status of your migrations:

rake seed:migrate:status

Example output:

database: seed-migrationdevelopment

 Status   Migration ID    Migration Name
--------------------------------------------------
   up     20160114153832  Add users
  down    20160114153843  Add more users
  down    20160114153851  Add even more users

Registering models

By default no models are registered, so running seed migrations won't update the seeds file. You have to manually register the models in the configuration file.

Simply register a model:

SeedMigration.register Product

You can customize the 'seeded' attribute list:

SeedMigration.register User do
  exclude :id, :password
end

This will create a seeds.rb containing all User and Product in the database:

# encoding: UTF-8
# This file is auto-generated from the current content of the database. Instead
# of editing this file, please use the migrations feature of Seed Migration to
# incrementally modify your database, and then regenerate this seed file.
#
# If you need to create the database on another system, you should be using
# db:seed, not running all the migrations from scratch. The latter is a flawed
# and unsustainable approach (the more migrations you'll amass, the slower
# it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.

ActiveRecord::Base.transaction do
  Product.create("created_at"=>"2014-04-04T15:42:24Z", "id"=>1, "name"=>"foo", "updated_at"=>"2014-04-04T15:42:24Z")
  Product.create("created_at"=>"2014-04-04T15:42:24Z", "id"=>2, "name"=>"bar", "updated_at"=>"2014-04-04T15:42:24Z")
  # ...
  User.create("created_at"=>"2014-04-04T15:42:24Z", "id"=>1, "name"=>"admin", "updated_at"=>"2014-04-04T15:42:24Z")
  # ...
end

SeedMigration::Migrator.bootstrap(20140404193326)

Note that seeds.rb is only generated in development mode. Production data will not be dumped in this process.

Checking for pending migrations

Check for pending data migrations:

SeedMigration::Migrator.check_pending!

If there are pending migrations, this will raise SeedMigration::Migrator::PendingMigrationError.

Adding seed_migrations to an existing app

If your app already contains seeds, using this gem could cause some issues. Here is the basic process to follow to ensure a smooth transition:

  • Clean your local database, and seed it, that can be done with rake db:reset
  • register all the models that were created in the original seeds file
  • run rake seed:migrate
  • At this point, your seeds file will be rewritten with all the create statements
  • Commit/Push the updated seeds file

Deployment notes

It is recommended to add the rake seed:migrate to your deploy script, so each new data migrations is ran upon new deploys. You can enable the extend_native_migration_task option to automatically run rake seed:migrate after rake db:migrate.

For Capistrano 3.x support, add this to your Capfile

require 'capistrano/seed_migration_tasks'

which provides the two cap tasks, which you can add to your deploy script or run on the command line:

cap {stage} seed:migrate
cap {stage} seed:rollback

Example

rails g seed_migration AddADummyProduct
class AddADummyProduct < SeedMigration::Migration
    def up
        Product.create!({
            :asset_path => "valentines-day.jpg",
            :title => "Valentine's Day II: the revenge!",
            :active => false,
            :default => false,
        }, :without_protection => true)
    end

    def down
        Product.destroy_all(:title => "Valentine's Day II: the revenge!")
    end
end

Configuration

Use an initializer file for configuration.

List of available configurations :

  • extend_native_migration_task (default=false)
  • ignore_ids (default=false)
  • migration_table_name (default='seed_migration_data_migrations'): Override the table name for the internal model that holds the migrations
  • use_strict_create (default=false): Use create! instead of create in db/seeds.rb when set to true

example:

# config/initializers/seed_migration.rb

SeedMigration.config do |c|
    c.migration_table_name = 'data_migrations'
    c.extend_native_migration_task = true

    c.register 'User' do
      exclude :id, :password
    end
    c.register 'Product'
end

Compatibility

At the moment, we rely by default on

ActiveRecord::Base.connection.reset_pk_sequence!

which is pg only.

If you need to use this gem with another database, use the ignore_ids configuration.

Runnings tests

RAILS_ENV=test bundle exec rake app:db:reset
bundle exec rspec spec

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

More Repositories

1

flag_shih_tzu

Bit fields for ActiveRecord
Ruby
495
star
2

sanitize_email

An Email Condom for your Ruby Server
Ruby
162
star
3

cacheable-flash

Gets the Rails flash object working with page cacheing.
Ruby
102
star
4

gem_bench

Static Gemfile Analysis
Ruby
77
star
5

capistrano_mailer

Capistrano Deployment Email Notification
Ruby
44
star
6

csv_pirate

100 Pirates agree creating CSVs is boring. Pirates prefer lazy. Pirates use CsvPirate.
Ruby
28
star
7

react-rails-benchmark_renderer

Concern::Instrumentation Plugin for React::Rails Render Benchmarking with a reference implementation
Ruby
14
star
8

debug_logging

Unobtrusive, configurable, drop-in debug logging useful when a call stack gets unruly
Ruby
11
star
9

require-rails-example

Holy Grail: Rails 4, RequireJS, jQuery, Backbone, Marionette, Handlebars, CoffeeScript, Slim, Asset Pipeline, all working with CDN Resources
Ruby
9
star
10

rspec-stubbed_env

Unobtrusively stub ENV keys and values during testing
Ruby
8
star
11

gitmoji-regex

πŸ”₯ A regular expression matching Gitmoji (a subset of Unicode Emoji) symbols
Ruby
7
star
12

each_in_batches

Makes it easy to execute really large computations on each row of really large data sets
Ruby
7
star
13

rack-toolbar

Provides an easy way to create Rack Middleware that injects things into the response body
Ruby
7
star
14

dry_views

Keep the views dry with content_for_with_default and friends!
Ruby
6
star
15

rspec-pending_for

Mark specs pending or skipped for specific Ruby engine (e.g. MRI or JRuby) / version combinations
Ruby
6
star
16

celluloid-io-pg-listener

LISTEN for NOTIFY events from PostgreSQL and Asynchronously Do Something with the payload
Ruby
6
star
17

activerecord-transactionable

Properly Implement ActiveRecord Transactions
Ruby
5
star
18

sir-du-bob

S(ecure)iR(Rails) D(ata)u B(ase)oB(ackup)
4
star
19

status_tag

Create HTML status tags or labels based on Ruby objects. Supports all Ruby web frameworks.
Ruby
4
star
20

anonymous_active_record

Faux Anonymous AR Models for testing Concerns, Observers, Decorators
Ruby
4
star
21

awesome_search

Helping de-nastify the 100+ line search methods of the world
Ruby
3
star
22

humorous_log_formatter

You want Humorous Log Levels and Color
Ruby
3
star
23

shiftable

Change ActiveRecord associations in a structured manner
Ruby
3
star
24

service_actor-promptable

TTY User Input plugin for service_actor gem
Ruby
3
star
25

stackable_flash

Allows flashes to stack intelligently, while preserving existing behavior of Rails' FlashHash.
Ruby
3
star
26

active_security

Disallow Unscoped Find for a Restful Night Sleep
Ruby
3
star
27

controller_validator

Simple Validations in the Controller
Ruby
3
star
28

pboling

Et moi, curated by my pet robot @autobolt
2
star
29

rspec-block_is_expected

Simplify testing of blocks in RSpec
Ruby
2
star
30

jquery.environment

jQuery plugin that is analogous to the config/environments files in Rails. Allows you to have environment specific configuration data (like FB app keys).
2
star
31

itunes_cleaner

DJs: Keep your Massive Libraries Clean and Organized
Ruby
2
star
32

silent_stream

ActiveSupport Stream Silencing - Without ActiveSupport
Ruby
2
star
33

rails_env_local

"development" is not always the best name for the local environment
Ruby
2
star
34

require_bench

Benchmark/Timeout/Rescue Ruby's `require`/`load` for Debugging Glory
Ruby
2
star
35

bash_step

Bash Step Function Library
Shell
1
star
36

qfill

Advanced Queue Transformation
Ruby
1
star
37

preferences_example

Uses ActiveRecord to store application preferences
Ruby
1
star
38

project-life

Personal Project Tracker
Ruby
1
star
39

js-cookie-calibre

A simple, lightweight JavaScript API for handling and namespacing configuration cookies
JavaScript
1
star
40

an_axe

TODO: one-line summary of your gem
Ruby
1
star
41

.github

My Community Project Defaults
1
star
42

include_with_respect

Find out if your include/extend hooks are misbehaving!
Ruby
1
star
43

spyke-connection_lambda

Spyke plugin allowing dynamic API connections per model, per thread
Ruby
1
star
44

railsbling.com

The RailsBling.com website
Rich Text Format
1
star
45

month-serializer

Serialize Month objects to Integer
Ruby
1
star
46

sequential_file

Sequential File makes determination of which file to process (read or write) easy!
Ruby
1
star
47

pretty_feed

Simple pass/fail logging colorization
Ruby
1
star
48

jquery.ellipsis

Yet Another jQuery Ellipsis Plugin... only better.
JavaScript
1
star
49

homebrew-kops-old

Kops for the lazy, deprecated, cloud engineer
Ruby
1
star
50

analog-reshaper

analog (gem) plugin allowing non-linear rescale of numbers
Ruby
1
star
51

jquery.cacheableFlash

A jquery plugin for the cacheable_flash ruby gem.
1
star
52

strict_states

State machine typos are the worst. Never again.
Ruby
1
star
53

simple_column-scopes

Simple ActiveRecord Scopes based on columns to tame wild models
Ruby
1
star