3

我現在處於想要爲每個使用rails generate model MyModel創建的模型添加另一個字段的情況。默認情況下,它將被分配一個ID以及created_atupdated_at的時間戳。如何修補內置在模型生成器中的導軌?

如何重新打開此生成器並將字段deleted_at添加到默認生成器?

+0

我不知道這是可能的,但你可以創建自己的發電機,可能調用原來,然後加入自己的領域。 –

回答

2

您可以創建運行生成器命令後創建的生成器文件的本地版本。這裏是原來只是供參考:https://github.com/rails/rails/blob/master/activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb

您需要像這樣:

class <%= migration_class_name %> < ActiveRecord::Migration[<%= ActiveRecord::Migration.current_version %>] 
    def change 
    create_table :<%= table_name %><%= primary_key_type %> do |t| 
<% attributes.each do |attribute| -%> 
<% if attribute.password_digest? -%> 
     t.string :password_digest<%= attribute.inject_options %> 
<% elsif attribute.token? -%> 
     t.string :<%= attribute.name %><%= attribute.inject_options %> 
<% else -%> 
     t.<%= attribute.type %> :<%= attribute.name %><%= attribute.inject_options %> 
<% end -%> 
     t.datetime :deleted_at # <------- ADD THIS LINE 
<% end -%> 
<% if options[:timestamps] %> 
     t.timestamps 
<% end -%> 
    end 
<% attributes.select(&:token?).each do |attribute| -%> 
    add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %>, unique: true 
<% end -%> 
<% attributes_with_index.each do |attribute| -%> 
    add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %> 
<% end -%> 
    end 
end 

,然後修補發生器類,它指向哪裏你保存的文件^

module ActiveRecord 
    module Generators # :nodoc: 
    class ModelGenerator < Base # :nodoc: 

     def create_migration_file 
     return unless options[:migration] && options[:parent].nil? 
     attributes.each { |a| a.attr_options.delete(:index) if a.reference? && !a.has_index? } if options[:indexes] == false 
     migration_template "#{ PATH_TO_YOUR_FILE.rb }", "db/migrate/create_#{table_name}.rb" 
     end 

    end 
    end 
end 

魔法門稍微調整一下,但這應該會有所斬獲。你也可以通過在該領域,當你運行生成器:

rails g model YourModel deleted_at:datetime

+0

不錯的做法,thx分享:) – Severin

+0

沒問題,很高興這會爲你工作。我知道很多人對猴子補丁有着複雜的感受,但是它完成了工作。哦,男人,你在2,999。我很想成爲投票,讓你超過3K,但我已經upvoted這個問題:) –

+0

歡迎@NickM Severin;) –