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

时间:2016-10-28 12:00:24

标签: ruby-on-rails activerecord rails-activerecord generator ruby-on-rails-5

我想在我使用rails generate model MyModel创建的每个模型中添加另一个字段。默认情况下,系统会为IDcreated_at分配updated_at以及时间戳。

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

1 个答案:

答案 0 :(得分:2)

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