I'm learning rails, and creating a simple question/answer app to test some of the concepts I've been introduced to. I used generate scaffold to create two model classes - Question and User.
The questions table consists of a question_number (int), question_text (string) and answer_text (string).
The users table has a uid (string), name (string) and current_question (int)
I then created a controller called gateway. I have the app working now where a user can go to the main page passing their UID as a parameter (eventually will be passed by a login function) and the app will display the question they are currently working on by grabbing the question_number which matches the user's current_question. Great.
I then created an answer method in the gateway controller. This method takes an answer the user types into a form and compares it to the answer in the database, redirecting the user to different pages depending on if the answer was right or wrong.
My issue - I set instance variables in the index method to set the current user and current question - but these do not persist to my answer method. What is the Rails best practice here? Do I:
1) Pass these as parameters to the answer method through the form, just like I pass the answer (seems inefficient when I've already created the instance vars in the controller, and now pass them back...) 2) Store these as vars in the session? 3) Store these in Flash? 4) Just look them up again in the answer method (don't like repeating code, and 2 calls for same info seems wasteful)
Am I even using the right structure for this app? What would you do in this instance, where you want to grab an attribute of a user (their current authorized question) and use it several times to query another part of the database (step 1 - get question matching user's authorized question, step 2 - check that answer user inputs is correct, step 3 - increment the user's auth question counter)
more info, @wukerplank
No plugins for session handling. Basically, my flow goes like this:
- "login" user (no login logic in this little test app, so I just pass the uid as a param in the URL)
- The gateway controller gets the user's current question with @question = Question.where(:question_number => @user.current_question).first
- User is displayed the question text and a form to enter answer
- Submit button calls my :answer action and passes the answer string
- Here is where I'd love to just call @question again, but can't because it is not persisted. So I either have to repeat step 2, or find a place to store the data I need to reference again. I'm assuming the DRY principles of Rails would advise against repeating Step 2, so I'm wondering where/how the best way to store these (and other variables I may need) are Thanks!