How to Edit Rails Scaffold Model generator

蓝咒 提交于 2021-02-08 06:41:12

问题


I am trying to customise rails default scaffold generators. For views I can do that by simply adding files under : lib/templates/erb/scaffold/

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 

I have tried adding files to lib/templates/rails/model/model_generator.rb

with codes like this :

 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.


回答1:


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

Here is my custom template

<% 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 -%>

Running scaffold

rails g scaffold property

File created

class Property < ApplicationRecord

   before_save :my_custom_method

   # my method
   def my_custom_method

   end

end



回答2:


To simplify, you can copy all the ActiveRecord model templates to your current Rails project with this command:

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


来源:https://stackoverflow.com/questions/46783879/how-to-edit-rails-scaffold-model-generator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!