Renaming the created_at, updated_at columns of ActiveRecord/Rails

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

    An updated anwser for Rails >= 5.1. I would suggest to use the ApplicationRecord that is available by default in your application and define the following:

    class ApplicationRecord < ActiveRecord::Base
      self.abstract_class = true
    
      class << self
        private
    
        def timestamp_attributes_for_create
          super << 'my_created_at_column'
        end
    
        def timestamp_attributes_for_update
          super << 'my_updated_at_column'
        end
      end
    end
    

    Note that you can also use this block on a specific model if you don't want to configure it for all your models.

    Note also that you should use strings and not symbols.

提交回复
热议问题