Migrations in Rails Engine?

前端 未结 6 1611
暗喜
暗喜 2020-12-12 14:48

I have multiple rails applications talking to the same backend and I\'d like them to share some migrations.
I setup a rails engine (with enginex), I can share anything (

6条回答
  •  情话喂你
    2020-12-12 15:15

    What i do, is add an InstallGenerator that will add the migrations to the Rails site itself. It has not quite the same behavior as the one you mentioned, but for now, for me, it is good enough.

    A small how-to:

    First, create the folder lib\generators\\install and inside that folder create a file called install_generator.rb with the following code:

    require 'rails/generators/migration'
    
    module YourGemName
      module Generators
        class InstallGenerator < ::Rails::Generators::Base
          include Rails::Generators::Migration
          source_root File.expand_path('../templates', __FILE__)
          desc "add the migrations"
    
          def self.next_migration_number(path)
            unless @prev_migration_nr
              @prev_migration_nr = Time.now.utc.strftime("%Y%m%d%H%M%S").to_i
            else
              @prev_migration_nr += 1
            end
            @prev_migration_nr.to_s
          end
    
          def copy_migrations
            migration_template "create_something.rb", "db/migrate/create_something.rb"
            migration_template "create_something_else.rb", "db/migrate/create_something_else.rb"
          end
        end
      end
    end
    

    and inside the lib/generators//install/templates add your two files containing the migrations, e.g. take the one named create_something.rb :

    class CreateAbilities < ActiveRecord::Migration
      def self.up
        create_table :abilities do |t|
          t.string  :name
          t.string  :description
          t.boolean :needs_extent      
          t.timestamps
        end
      end
    
      def self.down
        drop_table :abilities
      end
    end
    

    Then, when your gem is added to some app, you can just do

    rails g :install
    

    and that will add the migrations, and then you can just do rake db:migrate.

    Hope this helps.

提交回复
热议问题