In this lab we will explore cookies and sessions in rails. First we'll play with manually setting cookies on the front-end. Then we'll explore how cookies are used to create "sessions" that keep track of user data on the server-side.
Clone this repo, bundle, and run the server.
cd cookie_monster_app
bundle
rails s
Note: This rails application does not use a database or turbolinks.
####Challenges
To begin, visit http://localhost:3000/desserts
in your browser, with the Chrome Console open.
- Use the Chrome Console to manually set a cookie for the website to:
fav_color=blue
. When you refresh the page, a script running on the page will detect the color and apply it to the background of the page. - Manually add a second cookie (
can_has=yarly
) so that you can access the 3desserts#show
pages (/desserts/1
,/desserts/2
,/desserts/3
).
- The server is actually checking for this cookie in the HTTP Request Headers (see the
desserts#show
controller). Without this cookie, you will be blocked (redirected) from viewing all dessert pages!
- When a user clicks "Save as Favorite" on a
desserts#show
page, store the dessert id in the user's session. (Seeapp/controllers/desserts_controller.rb
) - Modify the
desserts#show
view to indicate whether the dessert shown is the user's favorite dessert (Seeapp/controllers/desserts_controller.rb
andapp/views/desserts/show.html.erb
).
- How would you compare the current_dessert to the user's favorite dessert? Can you use this comparison to create a "conditional view"?
- Stretch: Can you DRY up the controller code by using a
before_action
to check whether the user is logged in?
Pay special attention to
Resources > Cookies > localhost
in the Developer Console. The Cookies-view allows you to browse and delete cookies associated with the current domain.
What's the difference between a cookie and a session?
By the end of this lab you should be able to explain how and why these cookies are present in your browser: