从视图调用模型中的方法

发布于 2024-12-24 21:02:24 字数 399 浏览 2 评论 0原文

我正在尝试根据之前是否查看过项目、新评论等来评估需要在项目旁边显示哪个指示器。在我决定使用一个符号之前,我只想显示一个数字。

在我的报告模型中,我

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

像你 2024-12-31 21:02:24

尝试

def indicator
    #bunch of if elsif statements returning a number 0-3
end

您不需要 self,因为它[更正为]是类级别的方法。

Try

def indicator
    #bunch of if elsif statements returning a number 0-3
end

You don't need the self as it [corrected to] is a class level method.

月光色 2024-12-31 21:02:24

在您看来,您正在每个报表对象上调用实例方法indicator

report.indicator

但在您的模型中,您已经定义了一个类方法。因此,为了使其正常工作,请将您的指标方法也定义为实例方法:

def indicator
  #bunch of if elsif statements returning a number 0-3
end

In your view, you are calling an instance method indicator on each report object

report.indicator

But in your model, you have defined a class method. So, to make it work, define your indicator method as an instance method, too:

def indicator
  #bunch of if elsif statements returning a number 0-3
end
同展鸳鸯锦 2024-12-31 21:02:24

您的迭代变量report 用于遍历@reports 的每个实例。使用self.indicator,您可以声明一个类方法(通过self.name)。这样就可以调用 Report.indicator。您想要的是仅调用 Report 的单个实例,因此您可以在模型中定义方法指示器,如下所示:

def indicator
  #bunch of if elsif statements returning a number 0-3
end

现在这应该可以工作了!

Your iteration variable report is used for going through every instance of @reports. With self.indicator you are declaring a class method (via self.name). So this would make it possible to call Report.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:

def indicator
  #bunch of if elsif statements returning a number 0-3
end

Now this should work!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文