0

私のコントローラーの 1 つで、ある条件を指定してレイアウトを変更し、それ以外の場合は、親 ApplicationController が使用するデフォルトのレイアウトを維持したいと考えています (最初は「アプリケーション」でしたが、現在は他のいくつかを試しています)。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)>'
4

1 に答える 1

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
于 2015-02-28T22:27:08.740 に答える