
- Learning Ruby on Rails
- Rails 2.1 Home
- Rails 2.1 Introduction
- Rails 2.1 Installation
- Rails 2.1 Framework
- Rails 2.1 Dir Structure
- Rails 2.1 Examples
- Rails 2.1 Database Setup
- Rails 2.1 Active Records
- Rails 2.1 Migrations
- Rails 2.1 Controllers
- Rails 2.1 Views
- Rails 2.1 Layouts
- Rails 2.1 Scaffolding
- Rails 2.1 and AJAX
- Rails 2.1 Uploads Files
- Rails 2.1 Sends Emails
- Advanced Ruby on Rails 2.1
- Rails 2.1 RMagick Guide
- Rails 2.1 Basic HTTP Auth
- Rails 2.1 Error Handling
- Rails 2.1 Routes System
- Rails 2.1 Unit Testing
- Advanced Ruby on Rails 2.1
- Rails 2.1 Tips & Tricks
- Quick Reference Guide
- Quick Reference Guide
- Ruby on Rails 2.1 Useful Resources
- Ruby on Rails 2.1 - Resources
- Ruby on Rails 2.1 - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Ruby on Rails 2.1 - Session and Cookies
Sessions
To save data across multiple requests, you can use either the session or the flash hashes. A flash stores a value (normally text) until the next request, while a session stores data during the complete session.
session[:user] = @user flash[:message] = "Data was saved successfully" <%= link_to "login", :action => 'login' unless session[:user] %> <% if flash[:message] %> <div><%= h flash[:message] %></div> <% end %>
It's possible to turn off session management.
session :off # turn session management off session :off, :only => :action # only for this :action session :off, :except => :action # except for this action session :only => :foo, # only for :foo when doing HTTPS :session_secure => true session :off, :only=>:foo, # off for foo,if uses as Web Service :if => Proc.new { |req| req.parameters[:ws] }
Cookies
Following is the syntax for setting cookies −
# Set a simple session cookie cookies[:user_name] = "david" # Set a cookie that expires in 1 hour cookies[:login] = { :value => "XJ12", :expires => Time.now + 3600}
Following is the syntax for reading cookies −
cookies[:user_name] # => "david" cookies.size # => 2
Following is the syntax for deleting cookies −
cookies.delete :user_name
The option symbols for setting cookies are as follows −
value − The cookie’s value or list of values (as an array).
path − The path for which this cookie applies. Defaults to the root of the application.
domain − The domain for which this cookie applies.
expires − The time at which this cookie expires, as a +Time+ object.
secure − Whether this cookie is a secure cookie or not (default to false). Secure cookies are only transmitted to HTTPS servers.