1
假设您想要一个具有两种不同布局的博客。一个布局应该看起来像一个传统的Blog,包含一个标题,一个页脚,一个菜单等等。其他布局应该只包含博客文章,仅此而已。你将如何做到这一点,而不会失去与模型的连接,强制执行和渲染只有一个动作,并防止重复自己(DRY)?Rails 3:两个不同的布局使用相同的控制器和操作?
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 ction)。 current_uri = request.env['PATH_INFO']
将网址保存到变量中,以下if current_uri.include?('diashow')
将检查它是否是我们在routes.rb中配置的路线。
谢谢!没有这种不愉快的“diashow”行动,我得到了另一个条件。 – Marc 2011-12-29 09:52:54