You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Rails迁移生成逻辑及移除schema.rb顶部注释?

解决方案

一、修改迁移生成逻辑,让t.timestamps默认放在create_table开头

Rails支持通过自定义生成器模板修改迁移的生成规则,具体操作如下:

  1. 在项目根目录创建模板存放目录:
mkdir -p lib/templates/active_record/migration
  1. 创建自定义创建表迁移模板文件lib/templates/active_record/migration/create_table_migration.rb.tt,内容如下:
class <%= migration_class_name %> < ActiveRecord::Migration[<%= ActiveRecord::Migration.current_version %>]
  def change
    create_table :<%= table_name %> do |t|
      t.timestamps
<% attributes.each do |attribute| -%>
      t.<%= attribute.type %> :<%= attribute.name %>
<% end -%>
    end
  end
end

以后执行rails g scaffold或rails g model生成创建表的迁移时,t.timestamps会自动排在所有自定义字段的最前面。

二、移除schema.rb顶部的自动注释

在config/application.rb中添加以下配置:

config.active_record.schema_comment = nil

保存配置后,下次执行db:migrate时,schema.rb顶部的默认注释就不会再生成了。

内容的提问来源于stack exchange,提问作者CWarrington

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 22:47:22