2011-12-29 95 views
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中配置的路線。

回答

1

您將根據特定條件選擇要渲染的佈局。例如,URL中的參數,頁面正在呈現的設備等。

只需在您的choose_layout函數中使用該條件,而不是根據action_name決定佈局。 diashow操作是不必要的。

+0

謝謝!沒有這種不愉快的「diashow」行動,我得到了另一個條件。 – Marc 2011-12-29 09:52:54

相關問題