如何修补 rails 内置模型生成器?

How to patch rails built in model generators?

我现在的情况是,我想向使用 rails generate model MyModel 创建的每个模型添加另一个字段。默认情况下,它将被分配一个 ID 以及 created_atupdated_at 的时间戳。

如何重新打开此生成器并将字段 deleted_at 添加到默认生成器?

您可以创建在 运行 生成器命令之后创建的生成器文件的本地版本。原文仅供参考: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

然后修补生成器 class 并将其指向保存该文件的位置 ^

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