我们可以以干燥的方式使用inherited_resources的自定义操作吗?

时间:2009-12-15 16:56:18

标签: ruby-on-rails rest dry custom-action inherited-resources

我们的Location模型有自定义操作(:register)。支持代码非常类似于标准:更新。由于inherited_resources为我们提供了“模板”,我们从actions.rb复制了更新代码,将'update_attributes'更改为'register',flash消息反映了不同的操作。 这感觉不是很干。我们希望利用:更新。有什么想法吗?

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 个答案:

答案 0 :(得分:1)

Inherited resources为您可以在控制器上覆盖的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
相关问题