如何制作一个自定义生成器,它也可以在Rails中生成迁移

时间:2018-11-08 17:17:10

标签: ruby-on-rails generator

在这里,我正在制作一个自定义生成器。我还需要我的自定义生成器来生成带有一些预填充值的迁移(即迁移模板)

这是我的生成器文件:

class BlockGenerator < Rails::Generators::Base
  source_root File.expand_path('templates', __dir__)
  argument :model, type: :string

  def generate_model
    generate_block_model
  end

  private
  def generate_block_model
    template 'block_model_controller_template.template', "app/controllers/garcia_cms/#{model.pluralize.underscore}_controller.rb"
    template 'block_model_template.template', "app/models/#{model.singularize.underscore}.rb"
  end
end

我知道我需要添加此行才能使用迁移模板。

migration_template "migration.rb", "db/migrate/add_foo_to_bar.rb"

但是,每当我尝试使用生成器并将其行放置在generate_block_model方法中时,总是会收到一条错误消息

undefined method `migration_template' for #<BlockGenerator:0x00007f830cd155b0> (NoMethodError)

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您必须包含Rails::Generators::Migration模块:

class BlockGenerator < Rails::Generators::Base
  include Rails::Generators::Migration
  source_root File.expand_path('templates', __dir__)
  argument :model, type: :string

  def generate_model
    generate_block_model
  end

  private
  def generate_block_model
    template 'block_model_controller_template.template', "app/controllers/garcia_cms/#{model.pluralize.underscore}_controller.rb"
    template 'block_model_template.template', "app/models/#{model.singularize.underscore}.rb"
    migration_template "migration.rb", "db/migrate/add_foo_to_bar.rb"
  end
end