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

Learn More

How to use sessions in Ruby-on-Rails?

1080 Runs 13149 Views 1750 Copies

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

Saved

Saved

rogalvil 36

rogalvil
published 3 years ago

=README

==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
  end
  
  def alpha
    session[:alpha] = @country.alpha
    redirect_to countries_path
  end
  
  def code
    session[:code] = @country.code
    redirect_to countries_path
  end
  
  def remove
    session[params[:key]] = nil
    redirect_to countries_path
  end
  
  def reset
    reset_session
    redirect_to countries_path
  end
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).