Speed up development with full-stack environments for every branch.

Learn More

How to use sessions in Ruby-on-Rails?

1119 Runs 13613 Views 1829 Copies

This example demostrate how use sessions in Ruby-on-Rails.



rogalvil 36

published 4 years ago


==How to use sessions in Ruby-on-Rails?
This example demostrate how use sessions in Ruby-on-Rails.

== Objectives
Create session value
Update session value
Remove session value
Reset session all values

==Steps to replicate this example
1. Run 'bundle install'
2. Run 'rails g scaffold country name:string alpha:string code:string'
3. Copy content of seeds.rb 
4. Run 'rake db:migrate'
5. Run 'rake db:seed'
6. Modify routes.rb add these lines
  match 'name/:id', :controller=>:countries, :to => :name, :via=>:get, :as=>:name
  match 'alpha2/:id', :controller=>:countries, :to => :alpha2, :via=>:get, :as=>:alpha2
  match 'code/:id', :controller=>:countries, :to => :code, :via=>:get, :as=>:code
  match 'remove/:key', :controller=>:countries, :to => :remove, :via=>:get, :as=>:remove
  match 'reset', :controller=>:countries, :to => :reset, :via=>:get, :as=>:reset
  root 'countries#index'
7. Modify index.html.erb in country view folder and copy content of index.html.erb 
8. Modify countries controller with content of countries_controller.rb
  before_action :set_country, only: [:show, :edit, :update, :destroy, :name, :alpha, :code]

  def name
    session[:name] = @country.name
    redirect_to countries_path
  def alpha
    session[:alpha] = @country.alpha
    redirect_to countries_path
  def code
    session[:code] = @country.code
    redirect_to countries_path
  def remove
    session[params[:key]] = nil
    redirect_to countries_path
  def reset
    redirect_to countries_path
9. Press button Run

Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).