Search code examples
ruby-on-railsrubyruby-on-rails-3sessionsession-variables

Updating and accessing a session with Ruby on Rails


I'm working with ruby on rails 2.5.

I have an object "payment_plan". This object can change with a toggle behavior that changes, and I need to keep this object alive thorough all the session and at the end it should be save par of it in my mongo db. I need to access the latest status of the object always. The controller should be capable to update the object and the view should be able to access the latest state of the object.

Any insights on how to do something like this would be great :)

I have try to create a helper function in the application controller but had problem accessing it from the view.

Also I prefer not to save the state of the object in the db, because it will be too many db calls later.


Solution

  • To access a controller helper function from view, define it as a helper:

    class SomeController < ApplicationController
       helper def some_helper
       end
    end
    

    As for storing some data in session - it's ok, rails has nice session store mechanism for session[:my_object_prop] = 1/session[:my_object_prop] (see in official guide)

    But keep in mind, that:

    • by default session is stored in cookies, which are passed in headers from client browser with every request to your server (even to images, if they are on the same domain), so it's only practical to save small amounts of data there.
    • user can clear their's cookies and data will be lost (this is usually fine)
    • the opposite of the latter - a user may come to your app with session data from old version of your code