[英]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.