我的Locations#show
视图中有一个表单用于其他模型(PotentialClient
)。当我的表单验证失败时,重定向将清空所有字段,因为我需要为要加载的视图初始化新的potential_client
。
如何更改此设置,以便在验证失败后填充字段?
# LocationsController
def show
@potential_client = PotentialClient.new
end
# class PotentialClient < ActiveRecord::Base
validates_presence_of :name, :email, :phone
# PotentialClientsController
def create
@potential_client = PotentialClient.new(potential_client_params)
respond_to do |format|
if @potential_client.save
format.html { redirect_to Location.find(@potential_client.location_id), notice: 'Success!' }
else
format.html { redirect_to Location.find(@potential_client.location_id), notice: 'Failure!' }
end
end
end
# Form in /locations/show
<%= simple_form_for [ @location, @potential_client ] do |f| %>
<%= f.input :name %>
<%= f.input :email %>
<%= f.label :phone %>
<%= f.input :message %>
<%= f.hidden_field :location_id, value: @location.id %>
<%= f.submit "Submit" %>
<% end %>
答案 0 :(得分:1)
由于您要重定向到另一个页面,浏览器将发送新请求。所以服务器不知道在之前的请求中发生了什么。您需要使用会话在请求之间共享数据
def show
@potential_client = session[:potential_client] || PotentialClient.new
end
# PotentialClientsController
def create
@potential_client = PotentialClient.new(potential_client_params)
respond_to do |format|
if @potential_client.save
format.html { redirect_to Location.find(@potential_client.location_id), notice: 'Success!' }
else
session[:potential_client] = @potential_client
format.html { redirect_to Location.find(@potential_client.location_id), notice: 'Failure!' }
end
end
end