[英]How to control respond_to based on variable in Rails controller?
我在控制器中使用了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
过滤器可以访问request
其中有一个对象format
,你可以用来获取请求格式的方法。 更改before过滤器,以便如果格式为JavaScript,则允许进行请求处理。 就像是:
def superuser_required
return true if request.format == Mime::JS
redirect_to login_path unless current_user.superuser?
end
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
了解更多,对吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.