Rails从before_filter方法中设置布局 [英] Rails set layout from within a before_filter method

查看:129
本文介绍了Rails从before_filter方法中设置布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从Rails 3的before_filter方法中重置默认布局?

Is it possible to reset a default layout from within a before_filter method in Rails 3?

我有以下内容作为我的 contacts_controller.rb :

I have the following as my 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

我知道我可以放下...

I know I could just put...

layout 'admin', :only => [:index, :show]

...就在"ContactsController"中的"before_filter"之后,但是,由于我已经有很多其他控制器,并且许多操作已按管理员要求正确过滤,因此如果我可以重设在"admin_required"方法中从通常的布局"到管理员"的布局.

... right after "before_filter" in "ContactsController", but, as I already have a bunch of other controllers with many actions properly being filtered as admin-required ones, it would be much easer if I could just reset the layout from "usual_layout" to "admin" inside the "admin_required" method.

顺便说一句,通过放置...

BTW, by putting...

layout 'admin'

...在"admin_required"内部(如我在上面的代码中所尝试的),我收到未定义的方法错误消息.好像只在defs之外起作用,就像我对"usual_layout"所做的一样.

...inside "admin_required" (as I tried in the code above), I get an undefined method error message. It seems to work only outside of defs, just like I did for "usual_layout".

提前谢谢.

推荐答案

来自铁路指南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

这篇关于Rails从before_filter方法中设置布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆