【问题标题】:Redirect back with errors错误重定向回来
【发布时间】:2016-11-13 15:17:12
【问题描述】:

我有一个控制器:

controller/streets_controller.rb

class StreetsController < ApplicationController
  before_action :set_street, only: [:show, :edit, :update, :destroy]

  def show
    @house = @street.houses.build
  end

  .......

以及show 操作的视图。在那里我还展示了一个创建新街道房屋的表格:

views/streets/show.html.erb

<h1>Street</h1>
<p>@street.name</p>

<%= render '/houses/form', house: @house %>

当有人提交houses/form 时,请求转到houses_controller.rb

class HousesController < ApplicationController

  def create
    @house = House.new(house_params)

    respond_to do |format|
      if @house.save
        format.html { redirect_back(fallback_location: streets_path) }
        format.json { render :show, status: :created, location: @house }
      else
        format.html { redirect_back(fallback_location: streets_path) }
        format.json { render json: @house.errors, status: :unprocessable_entity }
      end
    end
  end

到目前为止,当有人插入正确的house_params 时,它会重定向回来并正确地创建房子

但是当有人插入错误house_params时,它会重定向_back,但它不会在表单中显示房屋错误,它会显示新房屋的表格@house = @street.houses.build

如何使用@house 对象重定向到StreetsController,以便显示错误并填写房屋表格?

谢谢

【问题讨论】:

  • 用户可能被重定向回哪些页面?

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


【解决方案1】:

通常,当创建操作出错时,您会呈现“新”视图而不是重定向回来。在您的情况下,您可以尝试重定向到街道显示路径,并将 @house 属性作为查询参数传递。然后在StreetsController#show 中,将房屋参数作为参数传递给build

【讨论】:

    猜你喜欢
    • 2020-10-22
    • 2017-03-12
    • 2017-07-14
    • 2015-12-11
    • 2020-04-24
    • 2012-06-08
    • 2011-08-10
    • 1970-01-01
    • 2015-04-28
    相关资源
    最近更新 更多