带错误重定向回来



有一个控制器:

控制器/streets_controller.rb

class StreetsController < ApplicationController
  before_action :set_street, only: [:show, :edit, :update, :destroy]
  def show
    @house = @street.houses.build
  end
  .......

show动作的视图。在这里,我还显示了一个创建新街道房屋的表单:

视图/街道/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时它会重定向回来但它不会显示表单中的房屋错误,它会显示新房屋的表单@house = @street.houses.build

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

谢谢

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

最新更新