Need explanations on best practices for sharing data between multiple methods of a controller

advertisements

I'm creating a file upload data processing app in rails. What is the best practice in making available the data to multiple controllers in rails? I have an action in my controller called FileProcessing#upload. This page (upload.html.erb) allows for the ability to upload and parses the csv file and stores into a nice old hash variable @file_data.

I have another method in my controller FileProcessing#index. This index method is there just to render the page index.html.erb. Now what? How can I show the data that was uploaded via the upload action in the index page? What is best practice for doing this? Could you explain some of the alternatives I have to be able to do this? I'm very new to ruby so a thorough explanation with my example would be amazing! Thank you in advance and sorry for the noob like questions. ;-)


The first thing you need to understand is that each each HTTP request will be routed to a precise Controller#action.
Rails will instantiate a new Controller object for each request, and will then destroy these instances as soon as the requests they are serving have been completed.

This means that two requests from the same client, even if concurrent or subsequent, will be be handled by two different instances of the Controller.

Also, if you decide to halt the execution of an action by calling redirect_to another_path, that will also be a different HTTP request, as rails will return the browser a 302 response with the new path as the destination of the redirection.

To answer your more practical question, you need to:

  1. store somewhere the state of your application (the file, the date and time of the upload, the user who uploaded it, etc)
  2. ensure that the index action has the means to retrieve that data.

On point 1, you can use the cookies, you can save that data in the DB and associate it to the user, etc.
On point 2, you can either retrieve that data using the user reference, or you can pass an explicit reference to the path helper, for example:

uploads_path
  # => /uploads

uploads_path(custom_parameter: "ninja-turtles", upload_id: 1337)
  # => /uploads?custom_parameter=ninja-turtles&upload_id=1337

done that, you'll have access to those parameters in the new action:

params[:upload_id]
  # => "1337"

Just be careful, because passing sensitive data as part of the URL string means that anyone can try to supply manually crafted parameters.


If you don't want to use different actions, on the other hand, you can just render the index.html.erb template at the end of the POST upload action.
In Rails, actions will default to render the templates of the same name, but of course you can customize that.