Ruby On Rails Helpers -- 在 helpers 中使用实例变量 [英] Ruby On Rails Helpers -- Using instance variables in helpers

查看:39
本文介绍了Ruby On Rails Helpers -- 在 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

它可以访问在 CourseSteps 控制器显示动作"中定义的 @course_step.在 helper 中使用实例变量是一种常见做法吗?

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?

推荐答案

根据此测验结果的详细程度,您可能实际上想要使用部分.在这种情况下,语法将是:

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 } %>

如果它相对简单并且你认为它应该在一个帮助器中,你应该简单地将 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.

这篇关于Ruby On Rails Helpers -- 在 helpers 中使用实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆