问题
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