问题描述
我想将此自定义生成器命名为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
如您所见,生成器使用了我提供给模型的列而不是模型本身
template "models/form.template","app/models/#{model}.rb" //code
rails g form test name:string
create app/models/name:string.rb //output
该如何解决?
解决方法
在Ruby on Rails Guide中,如果要将自定义命令行参数添加到自定义生成器,则必须将其声明为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
方法click here的更多信息。