How to generate create table migration file using Rails::Generators.invoke(“active_record:migration”)?

吃可爱长大的小学妹 提交于 2019-12-11 18:42:13

问题


When I used this code

Rails::Generators.invoke("active_record:migration","create_tests",{:behavior=>:invoke, :destination_root=>Rails.root})

to generate migration file, I got the following class generated:

class CreateTests < ActiveRecord::Migration
  def up
  end

  def down
  end
end

But what I want is this:

class CreateTests < ActiveRecord::Migration
  def change
    create_table :tests do |t|

      t.timestamps
    end
  end
end

I'm not aware of what parameters I need to pass inside the invoke method.


回答1:


You can create template file and use it for generation purposes.

    class CoolMessageGenerator < Rails::Generators::Base
      source_root File.expand_path('../templates', __FILE__)
      argument :model_name, :type => :string, :default => 'CoolMessage'

      def migration
        template 'cool_migration.rb',
                 File.join('db', 'migrate', "#{Time.now.to_i}_create_#{model_name.tableize}.rb")
      end
    end

and templates/cool_migration.rb in same directory:

class Create<%= model_name.pluralize %> < ActiveRecord::Migration
  def change
    create_table :<%= model_name.tableize %> do |t|
      t.timestamps
    end
  end
end 


来源:https://stackoverflow.com/questions/11397925/how-to-generate-create-table-migration-file-using-railsgenerators-invokeacti

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