2011-09-08 54 views
0

我有一個問題,我認爲我需要在同一個動作中使用重定向和渲染,我不斷得到雙渲染錯誤所以我想知道是否有人可以看到另一種方式。紅寶石/ Rails - 是否有這種雙渲染錯誤的解決方法(渲染+重定向)

我有一個選擇框和一個按鈕,允許用戶從一組城市中選擇導航到一個窗體。

<%= form_tag root_path, :method => :post do %> 
    <%= select_tag :city, options_for_select(%w{ Pittsburgh Philadelphia Austin }) %> 
    <%= submit_tag "Change City" %> 
<% end %> 

並在控制器中,我檢查城市參數,然後重定向到所需的頁面。

def index 
    if params[:city] == "Pittsburgh" 
    redirect_to pittsburgh_path 
    elsif params[:city] == "Philadelphia" 
    redirect_to philadelphia_path 
    elsif params[:city] == "Austin" 
    redirect_to austin_path   
    end 
    render :layout => false 
end 

但在此頁面上,我創建了一個只在該頁面上的特定佈局/設計,因此我只關閉了應用程序佈局。

我可以執行導航操作並同時關閉應用程序佈局的呈現嗎?

+1

問題是'redirect_to'等人。不要從動作返回,所以你只需確保你的違規'渲染'沒有達到。在最簡單的情況下,您可以將'render'放入條件的'else'塊中,所以只有在沒有重定向時纔會發生。 – numbers1311407

+0

您可以/應該在一個地方定義這些城市,並將其用於顯示和業務邏輯。在驗證了'params [:city]'在列表中後,您可以在控制器中執行'send:「#{params [:city] .downcase} _path」'來調用相關的路由幫助程序。 – coreyward

回答

6

是的,移動支票在before_filter

class MyController < ApplicationController 

    before_filter :redirect_customized_cities, :only => :index 

    def index 
    render :layout => false 
    end 

    protected 

    def redirect_customized_cities 
     case params[:city] 
     when "Pittsburgh" 
      redirect_to pittsburgh_path 
     when "Philadelphia" 
      redirect_to philadelphia_path 
     when "Austin" 
      redirect_to austin_path 
     end 
    end 
end 
+0

謝謝你的工作就像一個魅力 – ChrisWesAllen

0

或者您可以在任何重定向後執行return語句;例如在重定向將暫停方法鏈後返回true或false。