Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming the created_at, updated_at columns of ActiveRecord/Rails

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 with the overwritten methods is used.

like image 850
Rainer Blessing Avatar asked Apr 09 '09 10:04

Rainer Blessing


1 Answers

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
like image 100
Tadas T Avatar answered Oct 28 '22 11:10

Tadas T