Question

I'm building a JRuby on Rails app for a legacy database. None of the tables have a 'created_at' column (so I can just go ahead and add that), but all of them have a 'modtime' column instead of an 'updated_at' column. I can't change all of the column names from 'modtime' to 'updated_at' in the db since much of the java code and sql functions use this column name. It would be possible to simply add an 'updated_at' column to all the tables, but this would be confusing and less than ideal.

How I can get ActiveRecord to use 'modtime' as a column name instead of 'updated_at'?

Was it helpful?

Solution

Here's what you need to do for ActiveRecord to use modtime as its update column:

Create a file in the config/initializers directory named active_record_patch.rb

# config/initializers/active_record_patch.rb
module ActiveRecord
  module Timestamp      

    private

      def timestamp_attributes_for_update #:nodoc:
        [:modtime, :updated_on, :modified_at]
      end
  end
end

What you are doing here is overriding ActiveRecord::Timestamp's timestamp_attributes_for_update method which it uses to identify the names of its update attributes. The file needs to be put in config/initializers since all files in initializers get run once your Rails app loads.

This is a monkey patch and overrides the normal behavior of ActiveRecord::Timestamp which may break when you use a different version of ActiveRecord.

Hope it helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top