【问题标题】:How to patch rails built in model generators?如何修补模型生成器中内置的导轨?
【发布时间】:2017-03-11 07:40:06
【问题描述】:

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

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

【问题讨论】:

  • 我不确定这是否可能,但您可以创建自己的生成器,可能会调用原始生成器,然后添加您自己的字段。

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


【解决方案1】:

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

【讨论】:

  • 没问题,很高兴这对你有用。我知道很多人对猴子修补有不同的感受,但它可以完成工作。 :) 哦,伙计,你是 2,999。我很想成为让你超过 3K 的投票,但我已经对这个问题投了赞成票:)
  • 欢迎@NickM Severin ;)
猜你喜欢
  • 2013-12-26
  • 1970-01-01
  • 2020-09-30
  • 1970-01-01
  • 1970-01-01
  • 2012-04-23
  • 1970-01-01
  • 2019-03-01
  • 2012-03-24
相关资源
最近更新 更多