1

我们的 Location 模型有一个自定义操作 (:register)。支持代码与标准的 :update 非常相似。由于inherited_resources 为我们提供了“模板”,我们从actions.rb 中复制了更新代码,将“update_attributes”更改为“register”,flash 消息反映了不同的操作。这感觉不是很干燥。我们想使用:update 代替。有任何想法吗?

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
4

1 回答 1

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
于 2010-01-09T15:20:51.793 回答