如何访问' layout'父控制器?

时间:2015-02-28 21:55:25

标签: ruby inheritance layout controller alias-method

在我的一个控制器中,我希望在给定某些条件的情况下更改布局,否则保持父ApplicationController使用的默认布局(最初是#34;应用程序"最初,但是我正在尝试其他一些现在)。尝试访问"布局"使用alias_method但它似乎不起作用。我的代码:

class SomeController < ApplicationController
  alias_method :parent_layout, :layout
  layout :some_layout

  def some_layout
    if some_condition
      "new_layout"
    else
      :parent_layout
    end
  end
end

这会出错:

ActionController::RoutingError (undefined method `layout' for class `SomeController'):
  app/controllers/some_controller.rb:6:in `alias_method'
  app/controllers/some_controller.rb:6:in `<class:SomeController>'
  app/controllers/some_controller.rb:3:in `<top (required)>'

1 个答案:

答案 0 :(得分:0)

看起来你有很多选择。在这里查看文档(搜索“查找布局”) http://guides.rubyonrails.org/layouts_and_rendering.html

一些可能性,取决于您需要它的复杂程度:

# Proc-based
class ProductsController < ApplicationController
  layout Proc.new { |controller| controller.request.xhr? ? "popup" : "application" }
end

# Route based, :except and :only
class ProductsController < ApplicationController
  layout "product", except: [:index, :rss]
end

# Method-based
class OldArticlesController < SpecialArticlesController
  layout false

  def show
    @article = Article.find(params[:id])
  end

  def index
    @old_articles = Article.older
    render layout: "old"
  end
  # ...
end

我不确定你的代码是如何构建的,但看起来第一个代码可能对你有用:

class SomeController < ApplicationController
  layout Proc.new { |controller| controller.some_condition? ? "new_layout" : "application" }
end