0
0
Ruby on Railsframework~10 mins

Session handling in Ruby on Rails - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to set a session value in a Rails controller.

Ruby on Rails
session[:user_id] = [1]
Drag options to blanks, or click blank then click option'
Aflash[:user_id]
Bparams[:user_id]
Ccookies[:user_id]
Drequest.user_id
Attempts:
3 left
💡 Hint
Common Mistakes
Using cookies or flash instead of params to set session data.
Trying to assign a method call that doesn't return the user ID.
2fill in blank
medium

Complete the code to retrieve the current user ID from the session in a Rails controller.

Ruby on Rails
current_user_id = session[1]
Drag options to blanks, or click blank then click option'
A[:user_id]
B['user_id']
C.user_id
D(user_id)
Attempts:
3 left
💡 Hint
Common Mistakes
Using string keys instead of symbols.
Using dot notation which is invalid for session hash.
3fill in blank
hard

Fix the error in the code to clear the session in a Rails controller.

Ruby on Rails
def logout
  [1]
  redirect_to root_path
end
Drag options to blanks, or click blank then click option'
Asession.delete(:user_id)
Bsession.destroy
Csession.reset
Dsession.clear
Attempts:
3 left
💡 Hint
Common Mistakes
Using session.delete which removes only one key.
Using session.destroy which is not a valid method.
4fill in blank
hard

Fill both blanks to check if a user is logged in by verifying the session key.

Ruby on Rails
if session[1] && session[2] != nil
  # user is logged in
end
Drag options to blanks, or click blank then click option'
A[:user_id]
B['user_id']
C.user_id
D(user_id)
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing string and symbol keys.
Using dot notation which is invalid.
5fill in blank
hard

Fill all three blanks to create a session hash storing user name and role if the user is admin.

Ruby on Rails
if params[:role] == 'admin'
  session[1] = params[:name]
  session[2] = params[:role]
  flash[:notice] = 'Admin logged in as ' + session[3]
end
Drag options to blanks, or click blank then click option'
A[:user_name]
B[:user_role]
D[:admin]
Attempts:
3 left
💡 Hint
Common Mistakes
Using different keys for storing and retrieving the user name.
Using invalid keys like :admin which is not set.