Reputation: 21
I have a question dealing with state and having a web app remember user's input. I feel like the most obvious choice is a cookie, but I can't quite wrap my head around it. Let me elaborate on what I'm making.
I am making a simple web app for a user to take a multiple choice quiz. If a user starts a quiz and is the question one page, they select their answer and hit "submit". after that, my check_answer method in my quizzes_controller is called, and then the user is directed to the second question of the quiz.(http:localhost/quizzes/1?q=2)
My goal is that at the end of the quiz, we can calculate the results. I need to access the user's answer to question 1,2,3 etc when the user is done submitting.
Is a cookie the way to go? I don't have much experience with them and rails, but I had problems with it.
On another note, lets say you're on amazon.com and go to your shopping cart... all those items are stored there because they are stored in a cookie (or cache?) How do you think they store that?
How would I store an object like, ["answer1" => :answer, "answer2" => :answer] and then keep appending to the object after each question was answered?
Thanks!
Upvotes: 2
Views: 526
Reputation: 634
You could also try to use a cookie. Although if you need the data only for the current session, the first given answer is the prefered one :)
Upvotes: 0
Reputation: 940
It sounds like the "session" is the perfect area for this:
#In this case, the :answers session variable is an array
session[:answers] = []
session[:answers][0] = "first answer"
#on the next page
session[:answers][1] = "second answer"
#on the next page after that:
session[:answers][2] = "third answer"
#what the session[:answers] array looks like
#after three questions have been answered and stored:
["first answer", "second answer", "third answer"]
To answer your second question, you can also store a hash in the session, like this:
session[:answers] = {}
session[:answers]["answer1"] = "can be anything, string, symbol, another hash, array, int"
#next page:
session[:answers]["answer2"] = :answer
#what session[:answers] looks like on the third page:
{
"answer1" => "can be anything, string, symbol, another hash, array, int",
"answer2" => :answer
}
It is important to note that session
is itself simply a hash which retains state between page requests (this state is actually itself stored in a cookie underneath the hood, but you don't really have to worry about that too much... just don't store sensitive data in a session variable unless you are experienced in cryptography and web application security... and even then, still don't.)
So, you can store anything you want in a session variable:
session[:some_string] = "some string"
session[:some_hash] = { :value1 => "value 1", :value2 => 42 }
session[:some_number] = 42
session[:some_array] = ["how now brown cow", 15, "blue", :foom]
Upvotes: 2