简体   繁体   English

从视图中调用模型中的方法

[英]calling a method in model from view

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' 我得到undefined method 'indicator'

I thought I had a grip on how methods work... but clearly not, what am I doing wrong? 我以为我掌握了方法的运作方式......但显然不是,我做错了什么?

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. 你不需要自我,因为[纠正]是一个班级方法。

In your view, you are calling an instance method indicator on each report object 在您的视图中,您在每个报表对象上调用实例方法indicator

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

Your iteration variable report is used for going through every instance of @reports . 您的迭代变量report用于遍历@reports每个实例。 With self.indicator you are declaring a class method (via self.name ). 使用self.indicator您将声明一个类方法(通过self.name )。 So this would make it possible to call Report.indicator . 这样就可以调用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: 你想要的只是在一个Report实例上调用,所以你可以在模型中定义方法指示器,如下所示:

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

Now this should work! 现在这应该工作!

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

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