Question

In a Rails 4 multi-form application, I am trying to persist the form data in the session in case the user needs to go back and edit the form before submitting it.

Page 1 contains the form. Page 2 shows the data to user with the options to "Go Back" or "Submit" the form. Below is the code of the "Go Back" element:

<%= link_to 'Go Back', {controller: :partials, action: :index}, id: 'go_back_btn' %>

I also have my session and cookies being displayed in every page for troubleshooting:

<%= session[:formData].inspect %>

The Problem

When I click in the button (<a> tag actually) described above, I go back to Page 1 but my session is nil. I had values set in the cookies also, but they were set to nil as well.

Why is this happening? How can I fix this?

Was it helpful?

Solution

It turned out that the session was being reset explicitly in a controller's action (got rid of that) and the cookies can't be set from hashes or sessions it seems (can't confirm that behavior). So the solution was to parse the desired data form the session into JSON objects and send them to the view, where I used JavaScript to repopulate the form using the JSON it received.

In the controller:

def index
    # Conditionally store prepopulated form data from the session in some cookies
    if session[:myData]
        # Store the session data into instance variable and convert it to JSON
        @myData = session[:myData].to_json

        # Resetting session is optional
        reset_session
    end
end

In the view:

<% if @myData %>

    <script type="text/javascript">
        // Store values from the controller instance variables
        //   Need to call raw method so browser doesn't escape the quotation marks that exist in @myData (JSON object)
        var myData = <%= raw @myData %>;

        // Do something with you myData

    </script>

<% end %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top