Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
86 views
in Technique[技术] by (71.8m points)

Migrations in Rails Engine?

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 (controllers, views, models,...) but no migrations. I can't make it work !

I tried to create a file db/migrate/my_migration.rb but in my main application if I do :

  rake db:migrate

It doesn't load them.

After some googling it appears there was some recent work on this and it seems this has been merge to rails master. I'm with rails 3.0.3 do you see any way to make this work ?

Thanks !

question from:https://stackoverflow.com/questions/4526122/migrations-in-rails-engine

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 libgenerators<your-gem-name>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/<your-gem-name>/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 <your_gem_name>:install

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

Hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...