2013-10-13 64 views
0

希望有人可以用此指向正確的方向。DataMapper:在更新記錄前僅獲取更改的屬性

我想知道是否有方法在調用update方法之前使用DataMapper查看/獲取新舊屬性值並比較這些值。

該場景如下: 我有一個門票資源,我需要通知各個感興趣的各方關於對門票進行的更改。電子郵件通知時,付款狀態的變化,短信通知的時候,車票獲取的分配等

目前,我的票類中,我已經建立了這樣的回調/過濾器的支持人員:

before :update, :notify_changes 

def notify_changes 
    ticket = Ticket.get(self.id) # Get the original 
    if ticket.status != self.status 
     # Send out the email notification 
    end 
    if ticket.assigned_support != self.assigned_support 
     # Send out the SMS notification 
    end 
    # ... etc 
end 

有沒有更好或更有效的方法來做到這一點,而不是在ticket = Ticket.get(self.id)再次擊中數據庫?

+0

你更新回調之前不喜歡?或者'如果ticket.status!= self.status'? – AdamT

+0

我希望找到一種方法來做到這一點,而不需要再次在'ticket = Ticket.get(self.id)'處敲擊數據庫。如果對象知道它已經改變了,那麼希望它知道改變了什麼,對嗎? @AdamT – SeanNieuwoudt

回答

1

好的,我已經明白了這一點。這是作爲參考,如果別人發現自己問同樣的問題:

before :update, :notify_changes 

def notify_changes 
    # The status property has been changed 
    if !dirty_attributes[Ticket.properties[:status]].nil? 
     # old status: original_attributes[Ticket.properties[:status]] 
    end   

    # The assigned_support property has been changed 
    if !dirty_attributes[Ticket.properties[:assigned_support]].nil? 
     # old status: original_attributes[Ticket.properties[:assigned_support]] 
    end   
end 

靈感參考:This thread

1

是的,我指的是骯髒的,當我問。只是爲了增加一點意思別人會遇到這個問題。

有幾種方法可以調用來檢查屬性或模型對象的狀態。

- (Boolean) attribute_dirty?(name) 
- (Boolean) clean? 
- (Boolean) dirty? 
- (Hash) dirty_attributes # your choice 
- (Hash) original_attributes 

這些都是DataMapper::Resource一部分,可以在這裏找到: http://rubydoc.info/github/datamapper/dm-core/master/DataMapper/Resource