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
Or you could just make your own columns (DateTime) and just manually set the created_at column when you create and set the updated_at column when you update. That might be easier than the hack above. That's what I'm gonna do. Better yet, update rails to allow us to change these names.
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
In Rails 6.0 the instance method timestamp_attributes_for_create
does not exist anymore. This method got pushed up onto the class method level and is now private
https://apidock.com/rails/v6.0.0/ActiveRecord/Timestamp/ClassMethods/timestamp_attributes_for_create
This change was introduced with this commit https://github.com/rails/rails/commit/77ff9a0adbd1318b45203a76c64561b115245603
You could still overwrite self.timestamp_attributes_for_create
but I strongly suggest not to since the private API can be changed without further notice or bigger version bumps.
For Rails 6 I don't see a given "Rails way" to define custom created_at
/ updated_at
columns.
I suggest following this answer https://stackoverflow.com/a/18197702/924050
There is no simple way to do that. You can accomplish this either by overriding the ActiveRecord::Timestamp module, or by writing your own one to do the magic for you.
Here is how the magic works.