Search code examples
ruby-on-railsgeneratorscaffold

How to Edit Rails Scaffold Model generator


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.


Solution

  • 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