【问题标题】:Creating Rails Engine/Gem to modify existing model db table创建 Rails Engine/Gem 以修改现有模型数据库表
【发布时间】:2014-01-02 13:41:43
【问题描述】:

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

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

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

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

【问题讨论】:

  • 你为什么不看看他们是怎么做的设计源代码?喜欢github.com/plataformatec/devise/blob/master/lib/generators/…
  • 谢谢,我一直在与设计代码进行比较,但是那里发生了很多事情,我一直在努力寻找更简单的东西,以便在两者之间来回切换
  • 是的,有时它可能会令人困惑;)但是只要阅读代码,当您尝试理解它时,您会学到很多东西,尝试在您自己的 gem 中重现事物等等

标签: ruby-on-rails devise gem migration rails-engines


【解决方案1】:

因此,正如@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

class_nameplural_name 可以访问,因为我在终端中运行了 $ rails generate gem_name account

因此 class_name = 'account' 和复数名称 = '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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-24
    • 1970-01-01
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多