简体   繁体   English

Ruby On Rails助手 - 在助手中使用实例变量

[英]Ruby On Rails Helpers — Using instance variables in helpers

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". 它可以访问@course_step,它在CourseSteps控制器中显示“动作”。 Is this common practice to use instance variables in helpers? 这种常见做法是在助手中使用实例变量吗?

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. 如果它相对简单并且您认为它应该在帮助器中,您应该简单地将quiz作为参数。 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. 正如您所看到的,我使用Quiz类实现了我的示例。 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. 我不确定你的数据模型是什么样的,但是当你调用嵌套深度的属性时,通常表明出现了问题。

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... 打字少一点,无论如何......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM