Ruby on Rails/ActionController/Sessions

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Session[edit | edit source]

For a technical explanation of a Session take a look at the Wikipedia article about Sessions.

In Rails you have some options to store the session. Most of the time you want to store the session on the server, but with security-relevant data, you might want to consider storing the session inside a database. To change the session storage, edit config/initializers/session_store.rb and be sure to read on the RoR Website carefully.

Work with your session[edit | edit source]

As with the parameters, Rails provides a simple way of accessing your session. Consider following example:

def show_details
  #we may use this inside a user-specific action
  User.find(session[:current_user_id])
end

As you can see, you access the session in a similar way to the parameters. Storing a session isn't much more complicated:

def index
  #we have some code here to get the user_id of a specific (logged-in) user
  session[:current_user_id] = id
end

To destroy the session, just assign it a nil-value

session[:current_user_id] = nil

Displaying a Flash-message[edit | edit source]

Flashes are very special and useful part of a session. You may have already found it in one of the view files. Here is how they work: As said, Flashes are special. They exist only once and are destroyed after each request. Flashes are useful to display error messages or notices to the user (e.g. when he tries to log in or if his request resulted in an error)

Inside an action flashes can be used similar to:

def check
  #code that does some validation
  flash[:notice] = "Successfully logged in"
end

Inside the view you can access it like:

<% if flash[:notice] -%>
    <%= flash[:notice] %>
<% end -%>
<!-- maybe some HTML-Code -->
<% if flash[:warning] -%>
    <%= flash[:warning] %>
<% end -%>

As illustrated in the example, you are not limited to a single flash. Multiple flashes can be accessed by their name you have defined inside the controller.