我试图使用帮助方法来确定多个记录的属性值。下面是我正在尝试工作的基本功能(从视图来看):
<% if Baseline.where(subject_id: sub.subject_id).first.crf_status(crf) == 1 %>
<td bgcolor="#98FB98" >
<% else %>我的助手函数是crf_status(crf),,它看起来如下:
application_helper.rb
def crf_status(crf)
case crf
when Baseline then 'baseline_status'
when FollowUp3Week then 'follow_up_3_week'
...
end
end因此,一个有用的例子是,如果crf_status(Baseline)返回:
<% if Baseline.where(subject_id: sub.subject_id).first.baseline_status == 1 %>
<td bgcolor="#98FB98" >
<% else %>现在,错误是“基准的未定义方法'crf_status‘”。因此,根据我所读到的,也许我必须在每个控制器中引用ApplicationHelper?听起来不太对。请告诉我你的想法。
谢谢。
编辑。我忘了说明这一点: crf_status(crf)正在从数组基线FollowUp3Week.传递一个对象.
实际行的开头也是-> if crf.where(subject_id:.
发布于 2016-09-12 22:12:32
如果要返回要在上下文中调用的方法,请使用.send方法。
Baseline.where(subject_id: sub.subject_id).first.send(crf_status(crf))从您的方法返回的任何内容都将被执行。这是一个很好的元编程示例。您希望针对实例的类进行测试,所以在case行上使用.class方法。但是,您需要返回符号而不是字符串,所以请这样做:
def crf_status(crf)
case crf
when Baseline then :baseline_status
when FollowUp3Week then :follow_up_3_week
else :default
end
end编辑:类型比较用已更改的大小写
发布于 2016-09-12 21:59:06
当您做像.first.crf_status(crf)这样的方法链接时,您不会每次都得到一个新的全局范围。也就是说,要使此示例正常工作,需要将crf_status定义为Baseline模型上的实例方法。
从MVC设计的角度来看,从您的视图执行数据库查询(即where)是不可取的;您应该从控制器进行查询。在这里使用助手的选择完全是可选的。通过将其放入助手中,您所做的一切就是使您的视图之外的代码无法访问它。
下面是您应该在Baseline模型文件中编写的内容:
def crf_status(crf)
case crf
when Baseline then baseline_status
when FollowUp3Week then follow_up_3_week
end
end注意,baseline_status和follow_up_3_week实际上是隐式接收器self的方法调用。
发布于 2016-09-12 21:56:35
在模型的实例上调用"crf_status“,只能在视图和控制器上调用帮助程序。
你必须做这样的事
<% if crf.where(subject_id: sub.subject_id).first.send(crf_status(crf)) == 1 %>
<td bgcolor="#98FB98" >
<% else %>无论如何,这看起来像是一种奇怪的代码气味(在视图上查询是不对的,而且crf_status看起来像是应该在模型中移动的东西)。
https://stackoverflow.com/questions/39459293
复制相似问题