重定向回错误

Redirect back with errors

我有一个控制器:

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它redirects_back但是它没有在表格中显示房子错误,它显示新房子的表格@house = @street.houses.build

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

谢谢

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