Invalid form submission clears session in Rails 4

51 views Asked by At

I'm using a session to auto fill the first half of a form in Rails 4. The first time a customer submits a form (featuring their details and product details), the customers details are stored into a session. Upon subsequent forms (additional orders), the customer's details are pulled from the session and only the product details are required.

However, if an invalid form is submitted (i.e. when the form is empty but has required fields), when a new form is generated upon submission failure the customer details are no longer pulled from the session.

Upon investigating, it seems that the session itself is not getting cleared, as if I navigate off to a different url, and then come back to the form, the customer details are once again filled. Could it be something to do with how I generate my new form upon failure? My controller methods are shown below:

(reduced for brevity)

def new
  @order = Order.new
  @current_customer = Customer.find_by_id(session[:current_customer])
  if @current_customer
    @order.customer = @current_customer
  @order.build_customer
  end
end

def create
  @order = Order.new(order_params)
  @current_customer = Customer.find_by_id(session[:current_customer])
  if current_customer
    @order.customer = current_customer
  end
  if @order.save
    # Submit Success
    session[:current_customer] = @order.customer.id
    redirect_to thankyou_path(@order)
  else
    # If submission fails
    render :new
  end
end

Thank you

1

There are 1 answers

1
steve klein On BEST ANSWER

Yes it looks like you dropped the '@' in a couple of places in your Create action:

if current_customer
  @order.customer = current_customer
end

Should be:

if @current_customer
  @order.customer = @current_customer
end