【发布时间】:2011-12-29 06:16:35
【问题描述】:
假设您想要一个具有两种不同布局的博客。一种布局应该看起来像带有页眉、页脚、菜单等的传统博客。另一个布局应该只包含博客文章,仅此而已。在不丢失与模型的连接、仅强制执行和呈现一个动作并防止重复自己 (DRY) 的情况下,您将如何做到这一点?
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
两条不同的路线指向同一个位置(控制器/动作)。
current_uri = request.env['PATH_INFO'] 将 url 保存到一个变量中,下面的 if current_uri.include?('diashow') 检查它是否是我们在 routes.rb 中配置的路由。
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 layout controller action