2つの異なるレイアウトのブログが必要だとします。 1つのレイアウトは、ヘッダー、フッター、メニューなどを備えた従来のブログのように見えるはずです。他のレイアウトには、ブログ投稿のみが含まれている必要があります。モデルへの接続を失うことなく、1つのアクションの実行とレンダリングを強制し、自分自身を繰り返すのを防ぎません(DRY)。Rails 3:コントローラとアクションが同じ2つのレイアウト?
posts_controller.rb
class PostsController < ApplicationController
layout :choose_layout
# chooses the layout by action name
# problem: it forces us to use more than one action
def choose_layout
if action_name == 'diashow'
return 'diashow'
else
return 'application'
end
end
# the one and only action
def index
@posts = Post.all
@number_posts = Post.count
@timer_sec = 5
respond_to do |format|
format.html # index.html.erb
format.json { render json: @posts }
end
end
# the unwanted action
# it should execute and render the index action
def diashow
index # no sense cuz of no index-view rendering
#render :action => "index" # doesn't get the model information
end
[..]
end
は、おそらく私が間違った道を行きたいが、私は正しいものを見つけることができません。
更新:私のソリューションは、このようになります
:
posts_controller.rb
class PostsController < ApplicationController
layout :choose_layout
def choose_layout
current_uri = request.env['PATH_INFO']
if current_uri.include?('diashow')
return 'diashow'
else
return 'application'
end
end
def index
@posts = Post.all
@number_posts = Post.count
@timer_sec = 5
respond_to do |format|
format.html # index.html.erb
format.json { render json: @posts }
end
end
[..]
end
のconfig/routes.rbを
Wpr::Application.routes.draw do
root :to => 'posts#index'
match 'diashow' => 'posts#index'
[..]
end
二つの異なるルートがで指しています同じ場所(コントローラ/ a )。 current_uri = request.env['PATH_INFO']
はURLを変数に保存し、if current_uri.include?('diashow')
は、それがroutes.rbに設定したルートであるかどうかを確認します。
ありがとうございます!私はこの不愉快な「挑戦」をしないで別の状態を得ました。 – Marc