использование аргумента ActiveRecord в пользовательском генераторе

#ruby-on-rails #ruby #activerecord #migration #generator

#ruby-on-rails #ruby #activerecord #миграция #генератор

Вопрос:

я хочу, чтобы этот пользовательский генератор с именем form сгенерировал модель и создал ее файл миграции в db / migrate

это вывод :

 rails g form test name:string
      create  app/models/name:string.rb
      create  app/controllers/name:strings_controller.rb
      create  app/javascript/api/name:string.js
      create  app/javascript/component/name:strings.vue
      create  app/javascript/pages/name:string/index.vue
      create  app/javascript/pages/name:string/layout.vue
      create  app/javascript/store/actions/name:string.js
      create  app/javascript/store/getters/name:string.js
      create  app/javascript/store/modules/name:string.js
      create  app/javascript/store/mutations/name:string.js
      create  db/migrate/20200816162324_create_name:strings.rb
  

и это мой пользовательский класс генератора :

     require 'rails/generators/active_record'
    class FormGenerator < ActiveRecord::Generators::Base
      source_root File.expand_path('templates', __FILE__)
      source_root File.expand_path('templates', __dir__)
      argument :model, type: :string

def create_template

    template "models/form.template", "app/models/#{model}.rb"
    template "controllers/forms_controller.template", "app/controllers/#{model}s_controller.rb"
    template "javascript/api/form.template", "app/javascript/api/#{model}.js"
    template "javascript/pages/component/forms.template", "app/javascript/component/#{model}s.vue"
    template "javascript/pages/form/index.template", "app/javascript/pages/#{model}/index.vue"
    template "javascript/pages/form/layout.template", "app/javascript/pages/#{model}/layout.vue"
    template "javascript/store/actions/form.template", "app/javascript/store/actions/#{model}.js"
    template "javascript/store/getters/form.template", "app/javascript/store/getters/#{model}.js"
    template "javascript/store/modules/form.template", "app/javascript/store/modules/#{model}.js"
    template "javascript/store/mutations/form.template", "app/javascript/store/mutations/#{model}.js"
    migration_template "create_forms.template", "db/migrate/create_#{model}s.rb"

    
  end
  

как вы можете видеть, генератор использует столбец, который я дал ему для model, вместо самой модели

 template "models/form.template", "app/models/#{model}.rb"   //code
rails g form test name:string
          create  app/models/name:string.rb    //output
  

что я должен сделать, чтобы это исправить?

Ответ №1:

Из руководства по Ruby on Rails, если вы хотите добавить пользовательские аргументы командной строки в пользовательский генератор, вы должны объявить его как class_option . В этом случае ваши пользовательские аргументы представляют собой массив столбцов. Например:

 class FormGenerator < ActiveRecord::Generators::Base
  ...
  class_option :columns, type: :array, default: [] # Options :type and :default are not required
  
  def create_template
    @columns = options[:columns] # You can use this variable inside template
    ...
  end
end
  

Для получения дополнительной информации о class_option методе нажмите здесь.