是否可以从Rails 3中的before_filter方法中重置默认布局?
我将以下内容作为我的contacts_controller.rb:
class ContactsController < ApplicationController
before_filter :admin_required, :only => [:index, :show]
def show
@contact = Contact.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @contact }
end
end
[...]
end
然后在我的application_controller.rb中
class ApplicationController < ActionController::Base
layout 'usual_layout'
private
def admin_required
if !authorized? # please, ignore it. this is not important
redirect_to[...]
return false
else
layout 'admin' [???] # this is where I would like to define a new layout
return true
end
end
end
我知道我可以放...
layout 'admin', :only => [:index, :show]
...紧接在“ContactsController”中的“before_filter”之后,但是,由于我已经有一堆其他 Controller ,其中许多操作已被正确过滤为管理员所需的操作,如果我可以从“在“admin_required”方法中将“通常_布局”改为“管理员”。
顺便说一句,通过...
layout 'admin'
...在“admin_required”内部(如我在上面的代码中所尝试的),我收到未定义的方法错误消息。似乎只在defs之外起作用,就像我对“usual_layout”所做的一样。
提前致谢。
最佳答案
从Rails guides,2.2.13.2 Choosing Layouts at Runtime
:
class ProductsController < ApplicationController
layout :products_layout
private
def products_layout
@current_user.special? ? "special" : "products"
end
end
关于ruby-on-rails - Rails从before_filter方法中设置布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6672385/