【问题标题】:Can we use a custom action with inherited_resources in a DRY manner?我们可以以 DRY 的方式使用带继承资源的自定义操作吗?
【发布时间】:2009-12-15 16:56:17
【问题描述】:

我们的 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

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

    • 如果有人还在搜索这个:在 1.3 版的 Inherited Resources 中,传递给 update_resource 的第二个参数现在是一个数组。我必须在 update_resource 中使用 attributes[0] 才能获得与以前相同的行为。鉴于此更改,最好不要覆盖 update_resource。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多