ruby-on-rails - Rails从before_filter方法中设置布局

标签 ruby-on-rails layout before-filter

是否可以从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 guides2.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/

相关文章:

ruby-on-rails - rails : two sites - one database

ruby-on-rails - authlogic with_scope 不适用于 Rails 3 的多帐户应用程序

python - wxPython:在同一帧中显示多个小部件

ruby-on-rails - 如何在多个 RSpec 上下文中使用相同的共享示例和前置过滤器?

php - CakePHP v3.0 beforeFilter 正确语法

jquery - 使用 jQuery 在 Rails 中实现不显眼的动态表单字段

android - 在按钮内缩放可绘制对象?

python - 通过共享节点属性定位 networkx 节点

ruby-on-rails - :except not working in before_filter in application controller. 路由问题?

ruby-on-rails - 为什么安装 Heroku Toolbelt 会破坏我的 Rails 开发环境