开发者

Rails3 timestamp mapping to legacy table

I have a legacy table with a column for the l开发者_如何学JAVAast 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


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

alias_attribute :updated_at=, :lastcall=


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜