Ruby on rails 如何在Rails控制器中使用继承的资源跨不同的操作处理不同的场景

Ruby on rails 如何在Rails控制器中使用继承的资源跨不同的操作处理不同的场景,ruby-on-rails,Ruby On Rails,假设我有以下控制器,并希望将:edit、:update和:destroy限制为当前用户自己的foo class FooController < InheritedResources::Base before_filter :login_required respond_to :html def show @foo = Foo.find params[:id] show! end protected def collection @foo

假设我有以下控制器,并希望将:edit、:update和:destroy限制为当前用户自己的foo

class FooController < InheritedResources::Base
  before_filter :login_required
  respond_to :html

  def show
    @foo = Foo.find params[:id]
    show!
  end

  protected

  def collection
    @foos ||= Foo.all
  end

  def begin_of_association_chain
    current_user
  end
end
class FooController

我的问题很简单,也许也很幼稚:能否对上述内容进行重构,使其看起来更好?感觉好像我覆盖了太多的继承资源。

我通常使用一个before过滤器:lookup\u foo。(使用:except=>[:index,:new,:create]调用它)。然后我会有一行@foo=current_user.foos.find(params[:id])


索引操作也可以使用类似的方法,并且这两种方法都可以进行调整,以提供管理员更多的访问权限。

如果您希望通过当前用户方便地构建foo,我只需要使用before\u过滤器(见下文)。但是,对于编辑和销毁操作,我将实现一个授权库,如

class FooController[:create]
回复:html
私有的
def分配用户
build\u resource.user=当前用户
结束
结束
通过:

class FooController < InheritedResources::Base
  before_filter :login_required      
  before_filter :assign_user, :only => [:create] 
  respond_to :html

  private 
  def assign_user 
    build_resource.user = current_user 
  end
end