Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails session data - Store in a hash

I have a form on a rails view that submits data to a page that will represent a shopping cart summary page.

When I submit the data to the next page they are transmitted as follows according the console output.

"team"=>{"team_name"=>"Joe Blogs", "email"=>"[email protected]", "player1"=>"
3", "player2"=>"4", "player3"=>"5"}

I want to store this data is a session variable namely as a hash so if another team gets submitted to the summary page I can add it to the session as another hash entry. i.e. team[1], team[2]. Then I can access team[1].team_name, etc. and use it accordingly.

In summary, I want a user to be able to fill out a form and have it put into their cart. They can then go back and do the same again. Finally the can look at their cart and remove any records they don't want, clear the cart or submit what they choose into the database.

I can't find out how to do it or if it's even possible.

Any solutions or suggestions on how to implement this?

like image 340
Alan Avatar asked Nov 15 '15 23:11

Alan


1 Answers

You can easily store a hash in Rails session.

Example:

class SomeController < ApplicationController
  def some_action
    session[:cart] = {"team_name"=>"Joe Blogs", "email"=>"[email protected]", "player1"=>"3", "player2"=>"4", "player3"=>"5"}
  end
end

But, by default, Rails stores sessions in cookies, and a cookie size is limited to just 4 kilobytes of data, so if your hash is going to contain more than a few keys, you will need to use something else for session storage, e.g. the database.

To store session in the database you can use the activerecord-session_store gem.

like image 127
Dmitry Sokurenko Avatar answered Oct 02 '22 09:10

Dmitry Sokurenko