创建 Rails Engine/Gem 来修改现有的模型数据库表

Spa*_*lex 2 migration gem ruby-on-rails rails-engines devise

我之前问过这个但没有得到任何有用的答案,所以我再试一次......

我需要创建一个 gem 或引擎,将所需的列/属性添加到主应用程序中的现有模型。类似于设计 gem 可以创建模型的方式,或者将设计所需的属性附加到现有模型。

我的想法是 gem 需要一个类似于rails generate devise:install将创建所需迁移的安装脚本。

任何链接、教程或建议将不胜感激。

Spa*_*lex 6

因此,正如@23tux 建议的那样,我继续查看设计 gem 代码库并找到了我需要的解决方案。

lib/generators/{gem_name}我创建了一个名为的文件{gem_name}_generator中,我能够遵循https://github.com/plataformatec/devise/blob/master/lib/generators/devise/devise_generator.rb的模式并创建一个迁移以附加到应用程序中的现有模型。

require 'rails/generators/named_base'
require 'rails/generators/active_record'

module GemName
  module Generators
    class GemNameGenerator < ActiveRecord::Generators::Base

    include Rails::Generators::ResourceHelpers

    namespace "gem_name"

    desc "Creates GemName Migrations"

    source_root File.expand_path("../templates", __FILE__)

    def copy_migration
      migration_template "migration_existing.rb", "db/migrate/add_gem_name_to_#{plural_name.downcase}"
    end

      def migration_data
  <<RUBY
    ## Add active column to table
    t.datetime :started_trial, :default => Time.now, :after => :id
    t.boolean :active, :default => true, :after => :started_trial
    t.boolean :allowed_past_trial, :default => false, :after => :active
  RUBY
      end
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

class_name并且plural_name可以访问,因为在我运行的终端中$ rails generate gem_name account

因此class_name = 'account' 和plural_name = 'accounts'

migration_existing.rb 位于lib/generators/{gem_name}/templates并具有以下代码:

class AddGemNameTo<%= plural_name.camelize %> < ActiveRecord::Migration
  def self.up
    change_table(:<%= plural_name %>) do |t|
<%= migration_data %>
    end
  end

  def self.down
    # By default, we don't want to make any assumption about how to roll back a migration when your
    # model already existed. Please edit below which fields you would like to remove in this migration.
    raise ActiveRecord::IrreversibleMigration
  end
end
Run Code Online (Sandbox Code Playgroud)