如何根据Rails控制器中的变量控制respond_to?

时间:2010-03-21 17:21:44

标签: ruby-on-rails

困境

我在我的控制器中使用before_filter来限制对管理员的访问。但是,我想允许基于请求format访问某些方法的公共访问权限。请参阅index方法以了解我在说什么。

application_controller.rb

class ApplicationController < ActionController::Base

  # ...

  def current_user
    @current_user ||= User.find_by_id(session[:user])
  end

  def superuser_required
    redirect_to login_path unless current_user.superuser?
  end


end

items_controller.rb

class ItemsController < ApplicationController

  before_filter :superuser_required
  layout 'superuser'

  def index
    @items = Item.all
    respond_to do |format|
      format.html
      format.js # I want public to have access to this
    end
  end

  def show
    @item = Item.find(params[:id])
    respond_to do |format|
      format.html
    end
  end

  def new
    @item = Item.new
    respond_to do |format|
      format.html
    end
  end

  # remaining controller methods
  # ...

end

2 个答案:

答案 0 :(得分:3)

过滤器可以访问request对象,该对象具有format方法,可用于获取请求格式。更改您的前置过滤器,以便如果格式为JavaScript,则允许继续请求处理。类似的东西:

def superuser_required
  return true if request.format == Mime::JS
  redirect_to login_path unless current_user.superuser?
end

答案 1 :(得分:2)

比我预期的方式更容易

2天后

class FoosController < ActiveRecord::Base

  # use :except to open `show` action for public js access
  before_filter :superuser_required, :except => 'index'

  # before_filter does not apply here
  def index
    @foos = Foo.all

    respond_to do |format|

      # restrict behavior on html access for superusers
      format.html do
        superuser_required  # functions same as before_filter
      end

      # unrestricted on js access for public but only shows foo.id and foo.name
      format.js do
        render :text => @foo.to_json(:only => [:id, :name])
      end

    end
  end

  # restricted to superuser per before_filter
  def new
    @foo = Foo.new
    respond_to do |format|
      format.html
    end
  end

  # restricted to superuser per before_filter
  def show
    @foo = Foo.find(params[:id])
    respond_to do |format|
      format.html
    end
  end

end

当我在学习respond_to或者我原来的问题完全不连贯时,我完全错过了一些东西。不过,我只是再次阅读它,它似乎仍然是解决我的问题的唯一(也是最合适的)方式。

令人惊讶的是,我无法在网上找到任何此类行为的例子。那好吧。现在我对respond_to了解更多,对吧?