Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails engine, invoking container app's native migration generator

Others on SO have asked (and been answered) about how to write a migration template which will be copied to the container app just like any other template. We're writing a Rails engine which needs to work in multiple major versions of Rails, so we're hoping to find a way to use the app's native migration generator to generate migrations, rather than either having to maintain multiple templates, or needing to write a complex template which can handle multiple major versions.

I have seen in the Rails engine documentation (9.12) that you can invoke other generators like so:

generate "scaffold", "forums title:string description:text"

where the name of the generator, and its arguments, are single strings. However, the following doesn't work for us:

generate 'migration', 'create_table_name column1:type ...'

For us, regardless of Rails version, a migration file is created with the proper name, but empty up and down (or change) methods. So it's as if only the first argument is actually being received by the native migration generator.

Is there in fact a way to do this?

like image 260
dfaulken Avatar asked Jan 18 '17 20:01

dfaulken


1 Answers

This worked fine for me by using the camel case generate syntax:

lib/generators/test_generator.rb

class TestGenerator < Rails::Generators::Base                                  
  def build_table                                                              
    generate 'migration', 'CreateFoo name:string'                              
  end                                                                          
end

rails g test created the migration:

db/migrate/20170128040004_create_foo.rb

class CreateFoo < ActiveRecord::Migration[5.0]                                    
  def change                                                                      
    create_table :foos do |t|                                                     
      t.string :name                                                              
    end                                                                           
  end                                                                             
end  

So I think you just need to use the syntax CreateTableName and not create_table_name.

like image 172
trueinViso Avatar answered Nov 15 '22 05:11

trueinViso