How to override Rails' default migration generator template

夙愿已清 提交于 2019-12-06 09:53:37

I figured out a workaround for my case:

I create a Rails generator with this command(inside my Rails app directory) -

rails g generator my_migrator

It creates:

lib/generators/my_migrator/my_migrator.rb
lib/generators/my_migrator/templates
lib/generators/my_migrator/USAGE

Then I added this code to extend the rails migration generator in my generator by adding this code to my_generator.rb:

require 'rails/generators'
require 'rails/generators/active_record'
require 'rails/generators/actions/create_migration'

class MyGenerator < ActiveRecord::Generators::Base
  source_root File.expand_path('../templates', __FILE__)
  argument :attributes, :type => :array, :default => [], :banner => "field[:type][:index] field[:type][:index]"

  def create_migration_file
    set_local_assigns!
    validate_file_name!
    migration_template @migration_template, "db/migrate/#{file_name}.rb"
    # more code here as per requirement.
  end

  # more code below as per requirement..
end

Posted this here in a hope that it'll help someone some day in future.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!