从视图调用模型中的方法
我正在尝试根据之前是否查看过项目、新评论等来评估需要在项目旁边显示哪个指示器。在我决定使用一个符号之前,我只想显示一个数字。
在我的报告模型中,我
def self.indicator
#bunch of if elsif statements returning a number 0-3
end
认为
<% @reports.each do |report| %>
<%= report.indicator %>
<% end %>
我得到了 未定义的方法“指示器”
我以为我掌握了方法的工作原理......但显然不是,我做错了什么?
I am trying to evaluate which indicator needs to be displayed next to an item based on if it's been viewed before or not, new comments etc. Until I decide on a symbol to use, I just want a number to display.
in my Report Model i have
def self.indicator
#bunch of if elsif statements returning a number 0-3
end
in my view i have
<% @reports.each do |report| %>
<%= report.indicator %>
<% end %>
I get undefined method 'indicator'
I thought I had a grip on how methods work... but clearly not, what am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试
您不需要 self,因为它[更正为]是类级别的方法。
Try
You don't need the self as it [corrected to] is a class level method.
在您看来,您正在每个报表对象上调用实例方法
indicator
,但在您的模型中,您已经定义了一个类方法。因此,为了使其正常工作,请将您的指标方法也定义为实例方法:
In your view, you are calling an instance method
indicator
on each report objectBut in your model, you have defined a class method. So, to make it work, define your indicator method as an instance method, too:
您的迭代变量
report
用于遍历@reports
的每个实例。使用self.indicator
,您可以声明一个类方法(通过self.name
)。这样就可以调用Report.indicator
。您想要的是仅调用 Report 的单个实例,因此您可以在模型中定义方法指示器,如下所示:现在这应该可以工作了!
Your iteration variable
report
is used for going through every instance of@reports
. Withself.indicator
you are declaring a class method (viaself.name
). So this would make it possible to callReport.indicator
. What you want is to call just on a single instance of Report, so you can define the method indicator in your model like this:Now this should work!