如何编辑Rails脚手架模型生成器 [英] How to Edit Rails Scaffold Model generator
问题描述
我正在尝试自定义rails默认的脚手架生成器.对于视图,我可以通过在 lib/templates/erb/scaffold/
I am trying to customise rails default scaffold generators. For views I can do that by simply adding files under : lib/templates/erb/scaffold/
在这里,我添加了index.html.erb并对其进行了自定义,但是我想更改此命令生成的模型:
Here I have added index.html.erb and customized, but I want to change model that is generated by this command:
rails g scaffold model
我尝试将文件添加到lib/templates/rails/model/model_generator.rb
I have tried adding files to lib/templates/rails/model/model_generator.rb
具有如下代码:
module Rails
module Generators
class ModelGenerator < NamedBase #metagenerator
argument :attributes, :type => :array, :default => [], :banner => "field[:type][:index] field[:type][:index]"
hook_for :orm, :required => true
end
end
end
但这无济于事,在这方面我需要帮助,我需要覆盖哪些文件以及需要放置在何处.
But it is doing nothing I need help in this regard what file I need to override and where do I need to place.
推荐答案
Here is the Activerecord template. You need to put it in lib/templates/active_record/model/model.rb
as
~/D/p/p/generator_test> tree lib/
lib/
├── assets
├── tasks
└── templates #<========
└── active_record
└── model
└── model.rb
这是我的自定义模板
<% module_namespacing do -%>
class <%= class_name %> < <%= parent_class_name.classify %>
#custom method start
before_save :my_custom_method
# my method
def my_custom_method
end
#custom method end
<% attributes.select(&:reference?).each do |attribute| -%>
belongs_to :<%= attribute.name %><%= ', polymorphic: true' if attribute.polymorphic? %><%= ', required: true' if attribute.required? %>
<% end -%>
<% attributes.select(&:token?).each do |attribute| -%>
has_secure_token<% if attribute.name != "token" %> :<%= attribute.name %><% end %>
<% end -%>
<% if attributes.any?(&:password_digest?) -%>
has_secure_password
<% end -%>
end
<% end -%>
跑步支架
使用g脚手架属性
已创建文件
class Property < ApplicationRecord
before_save :my_custom_method
# my method
def my_custom_method
end
end
这篇关于如何编辑Rails脚手架模型生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!