2011-07-09 49 views
3

我有一個遺留表與上一次更新時間戳列。 現在我想告訴我的模型,rails屬性updated_at映射到legacy列。Rails3時間戳映射到遺留表

alias_attribute :updated_at, :lastcall 

現在我可以訪問列,但它,當我在更新對象不會得到更新。 那麼,我如何使用舊欄的軌道時間戳呢? 最好的, P

回答

1

我不知道是否有一個'正確'的方式做到這一點,但你可以在模型上使用before_save或before_update過濾器。

class LegacyModel < ActiveRecord::Base 
    before_update :update_lastcall 

    private 

    def update_lastcall 
    self.lastcall = Time.now 
    end 

end 

如果你不想讓模型混亂,你可以把它放到觀察者。

+0

嘿,這就是我解決它的方式,但它認爲可能有另一種解決方案將時間戳字段映射到您自己的數據庫列 – dc10

2

試着添加這個,這會替換setter方法。

alias_attribute :updated_at=, :lastcall= 
1

我也會喜歡到draw your attention to this,如果你的時間戳列名網站範圍(如我的是)。我不想混亂我的模型,幸運的是,你可以猴子補丁ActiveRecord::Timestamp。我把下面放到一個名爲lib/rails_ext/active_record.rb(我是一個組織怪胎)的目錄中,並在config/initializers/的一個初始化程序中聲明瞭一個require 'rails_ext/active_record'聲明。

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 

我的自定義屬性結束了:modified_time:created_date。您可以在其中一個列表中指定您的:lastcall列(我假設爲timestamp_attributes_for_update)。不需要使用您的模型。

相關問題