重定向到附加了参数的上一页

时间:2014-06-05 22:49:51

标签: ruby-on-rails

我有一个关于我这样链接的学校的评论页面;

<%= school_reviews_path(school_id: @school.id) %>

生成这样的链接;

http://address.com/school_reviews?school_id=1

但是,在评论下是一个表单,用于创建新的评论create schools_reviews controller

的行动

但是,在创建审核之后,我想重新呈现带有附带参数的页面,school_id=1

我尝试了几种类似这样的方法,但它没有工作,而是重定向到http://address.com/school_reviews而没有params意味着我们无法获取正确的信息。

def create
    @review = SchoolReview.new(params[:review])

    respond_to do |format|
      if @review.save        
        format.html { redirect_to school_reviews_path(:school_id => @review.school_id) }
        format.json { head :no_content }  
      else
        format.html { redirect_to school_reviews_path(:school_id => @review.school_id) }
        format.json { head :no_content }  
      end
    end
  end

任何想法都会很棒。

1 个答案:

答案 0 :(得分:0)

问题在于,您的表单很可能不会在任何地方设置学校ID,因此,让我们的代码更像它应该是的,首先设置这样的路线:

resources :schools do 
  resources :school_reviews
end

您的控制器名称没有变化,但实施将更改为如下:

class SchoolReviewsController < ApplicationController

  before_filter :load_school

  def create
    @review = @school.school_reviews.build(params[:review])

    respond_to do |format|
      if @review.save        
        format.html { redirect_to school_school_reviews_path(@school) }
        format.json { head :no_content }  
      else
        format.html { redirect_to school_school_reviews_path(@school) }
        format.json { head :no_content }  
      end
    end
  end

  protected 

  def load_school
    @school = School.find(params[:school_id])
  end

end

您还必须将视图中的form_for电话更改为:

<%= form_for( [@school, @review] ) do |f| %>
    Your form content here.
<% end %>

您的链接也将更改为:

<%= school_school_reviews_path(@school) %>

您可能还想将SchoolReview模型更改为Review,以从网址中删除school_school_

并且,像往常一样,阅读routes上的文档,了解正在发生的事情。