Ruby / Rails - 是否存在此双重渲染错误(渲染+重定向)的解决方法

时间:2011-09-08 14:31:11

标签: ruby-on-rails ruby-on-rails-3

我有一个问题,我认为我需要在同一个动作中使用重定向和渲染,并且我不断得到双重渲染错误,所以我想知道是否有人可以看到另一种方式。

我的表单中有一个选择框和一个按钮,允许用户从一组城市中进行选择以导航到。

<%= 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

但是在这个页面上,我创建了一个特定的布局/设计,只在该页面上,所以我只是关闭了应用程序布局。

我可以同时执行导航操作并关闭应用程序布局的渲染吗?

2 个答案:

答案 0 :(得分:7)

是的,将支票移到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

答案 1 :(得分:0)

或者您可以在重定向后执行return语句;比如在重定向之后返回true或false将停止方法链。