Forum: Ruby on Rails Newbie question; best way to store simple session data?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
C123fc303e9dab245efe2efe6be74f11?d=identicon&s=25 ken (Guest)
on 2007-05-01 07:28
(Received via mailing list)
As a first test project, I'm writing a little Rails app that simply
lets one browse the directory structure on the server. (Obviously,
this isn't intended for public deployment :-) ). One thing that needs
to be stored in a session is the currently browsed directory. What's
the best way to store such simple data? (I sorta think a database
table is overkill :-) )

Thanks,
Ken
Dfd6f9989147955682701da8227df8b4?d=identicon&s=25 Michael Wang (Guest)
on 2007-05-01 07:32
(Received via mailing list)
ken wrote:
> As a first test project, I'm writing a little Rails app that simply
> lets one browse the directory structure on the server. (Obviously,
> this isn't intended for public deployment :-) ). One thing that needs
> to be stored in a session is the currently browsed directory. What's
> the best way to store such simple data? (I sorta think a database
> table is overkill :-) )

Store it in a cookie.


--
Michael Wang
21f7ed21f11a809050594c82eab11d67?d=identicon&s=25 Robert Walker (Guest)
on 2007-05-01 18:01
(Received via mailing list)
Rails has a session management mechanism already built for you.  Just
use that.  Store your value in the session hash then you can just
configure Rails to store sessions either in a file (the default) or in
the database if you prefer that.

Excerpt from Agile Web Development with Rails page 105:
-----------------------------------------------------------
By default, Rails stores session information in a file on the server.
If you have
a single Rails server running, there's no problem with this. But
imagine that
your store application gets so wildly popular that you run out of
capacity on a
single-server machine and need to run multiple boxes. The first
request from
a particular user might be routed to one back-end machine, but the
second
request might go to another. The session data stored on the first
server isn't
available on the second; the user will get very confused as items
appear and
disappear in their cart across requests.
-----------------------------------------------------------

If you choose to store session data in the database just do this:
depot> rake db:sessions:create
exists db/migrate
create db/migrate/004_add_sessions.rb
depot> rake db:migrate

And here's a sample of storing an object in the session:

def find_cart
  unless session[:cart]             # if there's no cart in the
session
    session[:cart] = Cart.new   # add a new one
  end
  session[:cart] # return existing or new cart
end
This topic is locked and can not be replied to.