Renaming the created_at, updated_at columns of ActiveRecord/Rails

前端 未结 10 647
囚心锁ツ
囚心锁ツ 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:46

    I think NPatel's method is a right approach, but it is doing too much if you only need to change #created_at on a single model. Since the Timestamp module is included in every AR object, you can just override it per model, not globally.

    <= Rails 5.0

    class User < ActiveRecord::Base
      ...
      private
      def timestamp_attributes_for_create
        super << :registered_at
      end
    end
    

    Rails ~> 5.1

      private_class_method
      def self.timestamp_attributes_for_create
        # only strings allowed here, symbols won't work, see below commit for more details
        # https://github.com/rails/rails/commit/2b5dacb43dd92e98e1fd240a80c2a540ed380257 
        super << 'registered_at' 
      end
    end
    

提交回复
热议问题