2009-12-15 81 views
1

我們爲我們的位置模型提供了自定義操作(:註冊)。支持代碼與標準:更新非常相似。由於inherited_resources爲我們提供了一個「模板」,我們從actions.rb複製了更新代碼,將'update_attributes'更改爲'register',並且Flash消息反映了不同的操作。 這並不覺得非常乾燥。我們想利用:改爲更新。有任何想法嗎?我們可以以DRY方式使用帶有inherited_resources的自定義操作嗎?

class LocationsController < InheritedResources::Base 
    def register(options={}, &block) 
    #TODO: copied update from actions.rb. I expect there is a better way. 
    # All I changed was the flash message (to reflect the action) 
    # and the method call on the object (update_attributes -> register) 
    object = resource 

    if object.register 
     set_flash_message!(:notice, '{{resource_name}} was successfully registered.') 
     options[:location] ||= resource_url rescue nil 
     respond_with_dual_blocks(object, options, true, block) 
    else 
     set_flash_message!(:error) 
     respond_with_dual_blocks(object, options, false, block) 
    end 
    end 

回答

1

繼承資源爲您可以在控制器上覆蓋的CRUD操作提供幫助方法。您要查找的一個是

# Responsible for updating the resource in :update method. This allow you 
    # to handle how the resource is gona be updated, let's say in a different 
    # way then the usual :update_attributes: 
    # 
    # def update_resource(object, attributes) 
    #  object.reset_password!(attributes) 
    # end 
    # 
    def update_resource(object, attributes) 
    object.update_attributes(attributes) 
    end 

你覆蓋它是這樣的:

class LocationController < ApplicationController 
    inherit_resources 

    protected 

    def update_resource(object, attributes) 
    object.register(attributes) 
    end 
+0

櫃面任何人仍在尋找這樣的:在繼承的資源的1.3版本,傳遞給update_resource第二個參數是現在一個數組。我必須使用update_resource中的屬性[0]才能獲得與以前相同的行爲。鑑於此更改,最好不要覆蓋update_resource。 – 2012-09-20 01:19:02

相關問題