【问题标题】:How to Edit Rails Scaffold Model generator如何编辑 Rails 脚手架模型生成器
【发布时间】:2018-03-28 18:36:31
【问题描述】:

我正在尝试自定义 rails 默认的脚手架生成器。对于视图,我只需在以下位置添加文件即可:lib/templates/erb/scaffold/

这里我添加了 index.html.erb 并进行了自定义,但我想更改由此命令生成的模型:

rails g scaffold model 

我尝试将文件添加到 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

但是在这方面我需要帮助什么文件我需要覆盖以及我需要放置在哪里。

【问题讨论】:

  • 你想在生成的模型中改变什么?
  • 需要添加一些值 我想在 rails g 脚手架模型测试期间将一些自定义验证放入模型中如果可能,编辑模型和控制器
  • 手动创建模型文件怎么样?
  • 我没有明白你的意思我需要自动化只是想在脚手架中提供所有内容,它应该会产生魔力我有许多相同的模块,所以这将帮助我提高开发速度

标签: ruby-on-rails generator scaffold


【解决方案1】:

这是Activerecord 模板。你需要把它放在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 -%>

运行脚手架

rails g scaffold property

文件已创建

class Property < ApplicationRecord

   before_save :my_custom_method

   # my method
   def my_custom_method

   end

end

【讨论】:

  • 真棒如何对控制器做同样的事情,我需要把哪个文件放在 lib 文件夹中
【解决方案2】:

为简化起见,您可以使用以下命令将所有 ActiveRecord 模型模板复制到您当前的 Rails 项目中:

mkdir -p lib/templates/active_record/model && \
cp $(bundle info activerecord --path)/lib/rails/generators/active_record/model/templates/* lib/templates/active_record/model

【讨论】:

  • 如果我必须更改生成的路线并且我想向资源中添加一些东西,那真的会起作用
  • 脚手架路线的代码将在 Railties gem 中 - 在lib/rails/generators/rails/resource_route/resource_route_generator.rb 下。您可以将其复制到lib/templates/resource_route/ 并自定义它。
  • 如果没有更新,请确保重启spring或使用DISABLE_SPRING=true rails g model ...
猜你喜欢
  • 2018-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-11
  • 2016-03-19
  • 1970-01-01
相关资源
最近更新 更多