Reputation: 18338
I have a helper for a controller:
module CourseStepsHelper
def current_quiz_result
@course_step.step.step_quiz.quiz_attempts.where(:patient_id => current_user.id, :step_quiz_id => @course_step.step.step_quiz.id).first
end
end
It has access to @course_step which is defined in the CourseSteps controller show "action". Is this common practice to use instance variables in helpers?
Upvotes: 10
Views: 6326
Reputation: 3517
I haven't seen a good argument presented for either case, and stumbled onto this question when I was searching for an answer. Personally, I've been using the instance variables in helper methods where it's possible as this is the dryest approach across both helper and view. Rather than passing the instance variable from my view and defining my helper method to accept it, I can just use it directly in the helper. Slightly less typing, anyway...
Upvotes: 1
Reputation: 9003
Depending on the level of detail for this quiz result you may actually want to use a partial. In which case the syntax would be:
<%= render :partial => 'quiz/results', :locals => { :quiz => @quiz } %>
If it's relatively simple and you think it should be in a helper you should make simply make quiz
a parameter. Requiring views to provide a specific instance variable to use your helper would likely be frowned upon by other developers.
def quiz_result(quiz) # no need to call it "current" when we supply quiz
# do some stuff
end
It also looks to me that you may want to restructure your models in some way. As you can see I implemented my examples with a Quiz class. I'm not sure what your data model looks like but when you are calling properties that are nested that deep it's generally a sign that something is wrong.
Upvotes: 1