holden
holden

Reputation: 13571

rails session model

How can I treat important session info as if it were a model?

I've started toying with it, and some of it works. But I'm not sure what I'm missing? Does anyone know a good place to start or where I can find some good examples?

Also, I'm able to use the model to set session variables, but what about getting them from the model as opposed to always using session[:blah]... How can I retrieve them from the model instead?

class Cart
  attr_reader :items

  def initialize(session)
    @session = session
    @session[:cart] ||= []
    @items ||= session[:cart]
  end

  def add_rooms(new_rooms,startdate,days)
    #remove 0 values
    new_rooms.delete_if {|k, v| v == "0" }
    rooms = []
    new_rooms.each do |k, v|
      #rname = Room.find(k)
      #night = Available.find_by_room_id(k)
      rooms << {:room_id => k, :people => v, :no_days => days, :startdate => startdate} 
    end

    @session[:cart] = rooms
    #@items = rooms

  end

end

Upvotes: 3

Views: 8864

Answers (4)

GhettoDuk
GhettoDuk

Reputation: 24

You just need a method that returns the data you want from the session.

def blah
  @session[:blah]
end

If you need a lot of these, I would create a plugin that extends Class with a method that works similarly to attr_reader. Something like

session_reader :blah

Upvotes: 1

revgum
revgum

Reputation: 1187

+1 on the Railscast by Ryan Bates.

This type of thing works for me;

  def set_order_id(i)
    @cart_session[:order_id] = i
  end
  def has_order_id?
    @cart_session[:order_id]
  end
  def order_id
    has_order_id?
  end

Upvotes: 1

pantulis
pantulis

Reputation: 1705

There are some gotchas to be taken into account with this approach

  1. Depending on your session storage system, your session may grow too big if the objects you are putting in it are complex. The default store for sessions in Rails 2.3 are cookies so there will definitely be a limit imposed by the browser.
  2. If your model changes, after deploying your app users with old sessions will be presented with objects marshalled from the old model definitions, so they may get unexpected errors.

Upvotes: 2

John Topley
John Topley

Reputation: 115292

Upvotes: 1

Related Questions