如何编辑Rails脚手架模型生成器 [英] How to Edit Rails Scaffold Model generator

查看:78
本文介绍了如何编辑Rails脚手架模型生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试自定义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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆