dc10
dc10

Reputation: 33

Rails3 timestamp mapping to legacy table

I have a legacy table with a column for the last update timestamp. Now I do want to tell my model that the rails attribute updated_at is mapped to the legacy column.

alias_attribute :updated_at, :lastcall

Now I can access the column but it's not getting updated when i update the object. So how can I use the rails timestamps with an legacy column? Best, P

Upvotes: 3

Views: 639

Answers (3)

Ben Kreeger
Ben Kreeger

Reputation: 6344

I'd also like to draw your attention to this, if your timestamp column names are site-wide (as mine are). I didn't want to clutter up my models, and fortunately, you can monkey-patch ActiveRecord::Timestamp. I placed the below into a dir named lib/rails_ext/active_record.rb (I'm an organization freak) and called it with a require 'rails_ext/active_record' declaration in one of my initializers in config/initializers/.

module ActiveRecord
  module Timestamp
    private
    def timestamp_attributes_for_update #:nodoc:
      [:modified_time, :updated_at, :updated_on, :modified_at]
    end
    def timestamp_attributes_for_create #:nodoc:
      [:created_date, :created_at, :created_on]
    end
  end
end

My custom attributes ended up being :modified_time and :created_date. You'd specify your :lastcall column in one of those (timestamp_attributes_for_update, I'm assuming). No mucking with your models required.

Upvotes: 1

sarahhodne
sarahhodne

Reputation: 10116

Try to add this as well, which will alias the setter method.

alias_attribute :updated_at=, :lastcall=

Upvotes: 2

Dave A-R
Dave A-R

Reputation: 1169

I don't know if there's a 'proper' way of doing it, but you could do it with a before_save or before_update filter on the model.

class LegacyModel < ActiveRecord::Base
  before_update :update_lastcall

  private

  def update_lastcall
    self.lastcall = Time.now
  end

end

If you don't want to get the model messy you could put it into an Observer.

Upvotes: 1

Related Questions