0

In my controller's show method, I am having trouble creating an instance variable for each 'Subject' in my database. The "@pie_correct" variable works, but the problem is in the ".each" loop - I get the error "syntax error, unexpected '=', expecting keyword_end" How should I change this?

@pie_correct = TestQuestions.where(:correct => true).joins(:test).merge(Test.where(user_id: current_user))

Subject.all.each do |s|
  "@subject_ + #{s.id} + _correct" = @pie_correct.joins(:question).merge((Question.all).joins(:subject).merge(Subject.where(id: s.id)))
end

Thanks.

2 Answers 2

3

You're looking for the instance_variable_set method:

Subject.all.each do |s|
  instance_variable_set "@subject_#{s.id}_correct", @pie_correct.joins(:question).merge((Question.all).joins(:subject).merge(Subject.where(id: s.id)))
end

I also believe that you don't need the pluses within your interpolated string.

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

1 Comment

Thank you, that works. I was able to access the instance variables in the view in a similar manner with instance_variable_get("@subject_#{s.id}_correct")
2

System

Props to Chris Peters for his answer (which is right)

--

I wanted to raise a point about your system here. Why are you setting multiple instance variables?

At a loss for any other reason why, I'd recommend this goes against the DRY programming principles of Rails, as well as the Single Source Of Truth idea - which means you need to set data once, and use it as you wish.

I would personally set a single instance variable, and loop through that to pull the associative data.

2 Comments

I'd have to agree with you. At least put all of the values into an array. When answering the question, I could only assume that @user3291025 needed it set that way for some specific reason.
Thanks Rich, I'm still learning the ropes. I have re-written the controller instance variable as: @subjects = Subject.all, and am looping through the single instance variable in the view.

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.