【问题标题】:rails g migration "command" to generate column rename migration?rails g 迁移“命令”生成列重命名迁移?
【发布时间】:2013-12-14 23:02:55
【问题描述】:

我想自动生成一个如下所示的迁移文件:

class RenameDatabaseColumn < ActiveRecord::Migration
  def change
    rename_column :events, :subcategory, :subcategory_id
  end
end

有没有办法格式化我的

rails g migration ~rename_column_events_subcategory_subcategory_id~

或者类似的东西来自动生成那个文件?

【问题讨论】:

标签: ruby-on-rails rails-migrations


【解决方案1】:

不,没有“重命名”列的自动生成命令。

Refer Source Code。自动生成器只理解“to”、“from”、“add”、“remove”、“join_table”、“create”

【讨论】:

    【解决方案2】:

    目前不存在用于重命名列的自动生成命令。 您需要手动更改它,然后运行rake db:migrate

    【讨论】:

      【解决方案3】:

      您可以为rename_column 创建自定义生成器

      # lib/generators/ext/rename_column.rb
      ActiveSupport.on_load(:active_record) do
        ActiveRecord::Generators::MigrationGenerator.class_eval do
          alias :origin_create_migration_file :create_migration_file
          def create_migration_file
            if file_name =~ /^rename_(.*)_to_(.*)_on_(.*)/
              @old_column = $1
              @new_column = $2
              @table_name = normalize_table_name($3)
              @migration_template = File.join(Rails.root, "lib", "generators", "ext", "templates", "rename_column_migration.rb")
              
              validate_file_name!
              migration_template @migration_template, File.join(db_migrate_path, "#{file_name}.rb")
            else
              origin_create_migration_file
            end
          end
        end
      end
      
      # lib/generators/ext/templates/rename_column_migration.rb.tt
      class <%= migration_class_name %> < ActiveRecord::Migration[<%= ActiveRecord::Migration.current_version %>]
        def change
          rename_column :<%= table_name %>, :<%= @old_column %>, :<%= @new_column %>
        end
      end
      
      # config/initializers/ext_core.rb
      require File.join(Rails.root, "lib", "generators", "ext", "rename_column.rb")
      

      现在你可以像这样自动生成rename_colum

      $ rails g migration RenameTitleToNameOnProducts
      create    db/migrate/20210906044147_rename_title_to_name_on_products.rb
      
      # result
      class RenameTitleToNameOnProducts < ActiveRecord::Migration[6.1]
        def change
          rename_column :products, :title, :name
        end
      end
      

      【讨论】:

        猜你喜欢
        • 2016-02-02
        • 2020-10-03
        • 2012-09-03
        • 2018-07-24
        • 1970-01-01
        • 2013-02-16
        • 1970-01-01
        • 2013-09-13
        • 2011-06-17
        相关资源
        最近更新 更多