我在我的控制器中使用before_filter
来限制对管理员的访问。但是,我想允许基于请求format
访问某些方法的公共访问权限。请参阅index
方法以了解我在说什么。
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
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
答案 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
了解更多,对吧?