Reputation: 6694
I have a form on my Locations#show
view for a different model (PotentialClient
). When my form fails validations, the redirect empties all fields because I need to initialize a new potential_client
for the view to load.
How can I change this so that after a failed validation, the fields populate?
# 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 %>
Upvotes: 0
Views: 71
Reputation: 15985
Because you are redirecting to another page, browser will send new request. So server wouldn't have any idea what happened in previous request. You need to use session to share data between requests
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
Upvotes: 1