Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'

I thought I had a grip on how methods work... but clearly not, what am I doing wrong?

like image 805
bennett_an Avatar asked Jan 02 '12 20:01

bennett_an


People also ask

Can we call controller method in model rails?

As the two answers said, you should not be calling controller methods from your models. It is not recommended. Read into Model View Controller (MVC). To keep things independent.


3 Answers

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.

like image 89
Michael Durrant Avatar answered Oct 14 '22 09:10

Michael Durrant


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
like image 24
Marek Příhoda Avatar answered Oct 14 '22 09:10

Marek Příhoda


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!

like image 2
Tim Brandes Avatar answered Oct 14 '22 09:10

Tim Brandes