1

In this quiz I'm building when an answer is clicked, I want the @taken instance variable to change from "No" to "Yes"

Here i assign it to "No" if nil in my show action

def show
    if @taken == nil
        @taken = "No"
    end
end

Then here I update it to "Yes" if the submit_answer action is called. Thing is the flash notices are working correctly when an answer is clicked so I know that this action is working. But for some reason it doesn't update the @taken variable. Why?

controller#action

def submit_answer
    @answer = Answer.find(params[:answer_id])

    if @answer.correct_answer == true
        flash[:notice] = "You did it!"
        @taken = "Yes"
        redirect_to :back

    else
        flash[:notice] =  "Sorry wrong answer!"
        @taken = "Yes"
        redirect_to :back   
    end
end

view.html.haml

- @question.answers.each do |answer|
            .sub-panel.top-padding.green-hover
                - if @taken == "No"
                    %li.padding-left= link_to "#{answer.content}", submit_answer_path(answer_id: answer.id)
                - else 
                    %li.padding-left= answer.content

= @taken.inspect

routes.rb

get 'quizzes/answer/:answer_id', to: 'quizzes#submit_answer', as: :submit_answer

What's happening is it's setting @taken to "No" correctly in the show action. But then after the submit_answer action is called and the flash notice displays, it doesn't update the @taken instance variable to yes.

2 Answers 2

2

In rails controller you will not get instance variable(@variable) of one action in another action. For this you have to create class variable (@@variable).

For more you can go through this link

Sign up to request clarification or add additional context in comments.

2 Comments

I'm pretty sure class variable is the wrong way to go.
Yes you are right but in scenario it's necessary. There are other ways also like maintaining things using form variable and attribute accessors. But I have answered as per question.
2

Controller instance variables are not remembered between requests.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.