2012-04-22 64 views
0

所有相關型號我有一個2級嵌套模型:觸摸的CRUD

country <- state <- city 

目前,在每個控制器,要求所有CRUD操作,我會找到它的父模型和運行.touch每個模型。例如:

# cities_controller.rb 
def update 
    @state = State.find(params[:state_id]) 
    @country = Country.find(@state.id) 
    ... 
    @state.touch 
    @country.touch 
end 

對於每一個動作statecity,我會觸摸時CRUD成功完成其父(及其母公司的母公司)。

有沒有DRYer的方法可以做到這一點?我知道autosave選項,但它只適用於新創建的關聯記錄。我還想包括銷燬,更新的記錄。如果其中一個city發生更改,則它將被加上時間戳以反映已更改的內容,即statecountry

非常感謝。

+0

請記住,這些代碼並不屬於一個控制器,它屬於模型。 – 2012-11-11 13:01:30

回答

1

如果我是你,我更願意在這個模型中重寫touch函數。

class State < ActiveRecord:Base 
    def touch 
    self.updated_at = Time.now 
    self.state.touch 
    end 
end 

class City < ActiveRecord:Base 
    def touch 
    self.updated_at = Time.now 
    self.state.touch 
    end 
end