2

我想知道是否有任何方法可以在应用程序控制器中为索引和显示操作定义默认响应,并能够在需要一些自定义的其他控制器中覆盖。

我认为举个例子会更容易。

我正在使用 InheritedResources、CanCan/Authlogic 和 WickedPDF gem 来生成我的 pdf 文件并授权用户。我想知道我是否可以干掉我的代码。

这是我所拥有的

class ProductsController < InheritedResources::Base
  load_and_authorize_resource
  respond_to :html, :xml, :json, :pdf

  def index
    @products = Product.page(params[:page])
    index! do |format|
      format.pdf do
        render :pdf => pdf_file_name,
               :show_as_html => params[:debug].present?
      end
    end
  end  

  def show
    show! do |format|
      format.pdf do
        render :pdf => pdf_file_name,
               :show_as_html => params[:debug].present?
      end
    end
  end
end



class CustomersController < InheritedResources::Base
  def index
    index! do |format|
      format.pdf do
        render :pdf => pdf_file_name,
               :show_as_html => params[:debug].present?
      end
    end
  end  

  def show
    show! do |format|
      format.pdf do
        render :pdf => pdf_file_name,
               :show_as_html => params[:debug].present?
      end
    end
  end
end

这工作得很好。但是,我需要在要为其生成 pdf 的每个控制器中定义 format.pdf 似乎是多余的。有没有办法将它移动到应用程序控制器或使用继承的资源指定某处,然后在每个控制器的基础上覆盖它?有任何想法吗?

谢谢

4

1 回答 1

2

好的,我为其他感兴趣的人提出了以下解决方案。

我想我可以添加一个从继承自 ApplicationController 的 InheritedResources 继承的控制器,然后让我的所有其他控制器都从它继承(除了一些将直接从应用程序控制器继承的特殊情况(例如 HomeController,它不'除了索引之外没有任何动作,并且不绑定到任何特定模型) - 这样我可以定义某些默认值 - 我继续在我的所有控制器(如 response_to)中使用,并且仍然享受 InheritedResources gem 的好处。

class DefaultInheritedResourcesController < InheritedResources::Base
  # For CanCan authorization - pretty much makes it application wide, without the need
  # to define it in each controller. Can still override it in ability.rb by making    
  # a resource readable to all users with a session.
  #  if user
  #    can :read, [Product]
  #  end 
  # Also for controllers that need special treatment, you can just inherit from ApplicationController
  # and override with skip_authorization_check - but for my app it's rare (only HomeController),
  # most of controllers deal with some kind of resource - so this is a useful convention for 99% of use cases. 

  load_and_authorize_resource 
  respond_to :html, :json, :xml, :pdf

  # format pdf needs to be redefined on those actions where index! or show! are called.
  def index
    super do |format|
      format.pdf do
        render :pdf => pdf_file_name,
               :show_as_html => params[:debug].present?
      end
    end
  end  

  def show
    super do |format|
      format.pdf do
        render :pdf => pdf_file_name,
               :show_as_html => params[:debug].present?
      end
    end
  end  
end   

然后在我的 ProductController 中我可以做到这一点(注意我的 ProductController 是从哪里继承的。

class ProductsController < DefaultInheritedResourcesController
  def index
    @products = Product.page(params[:page])
    super
  end 
end

希望这会帮助某人。

于 2012-03-12T23:01:29.737 回答