Renaming the created_at, updated_at columns of ActiveRecord/Rails

前端 未结 10 645
囚心锁ツ
囚心锁ツ 2020-11-28 07:02

I want to rename the timestamp columns defined in timestamp.rb . Can the methods of timestamp.rb be overwritten? And what has to be done in the application that the module w

10条回答
  •  自闭症患者
    2020-11-28 07:56

    A sol'n which does not use a monkey patch; use the reversible block during your migration:

    class CreateTest < ActiveRecord::Migration
      def change
    
        create_table :test do |t|
        end
    
        # set the timestamp columns default to now()
        reversible do |dir|
          dir.up do
            tables = [
              :test
            ]
            tables.each do |t|
              execute <<-SQL
                ALTER TABLE #{t.to_s}
                  add column created timestamp without time zone default now();
              SQL
              execute <<-SQL
                ALTER TABLE #{t.to_s}
                  add column updated timestamp without time zone default now();
              SQL
            end
          end
          dir.down do
            # no need to do anything, the rollback will drop the tables
          end
        end
    
      end
    end
    

提交回复
热议问题