For counting average

I am passing hard time with ruby on rails …I was trying to count the average of a whole table…at first I calculated avarage of eah column then average of the average values but it is giving me an error- here are my codes and error- error-

NoMethodError in

Rate_schools#index Showing /home/vmuser/workspace/project3 -3/app/views/rate_schools/index.html.erb where line #36 raised:

undefined method `+' for nil:NilClass

Extracted source (around line #36):

33:
34:
35:
36: Average <%=((@avg1+@avg2+@avg3+@avg4+@avg5+@avg6+@avg7+@avg8)/8)%>
37: <% end %>
38:
39: </tr>

codes In controller: def index

    @school=School.find(params[:id])
      @rate_school =@school.rate_schools.build
    

 @avg1=@school.rate_schools.average(:library)

@avg2=@school.rate_schools.average(:careercenter) @avg3=@school.rate_schools.average(:location) @avg4=@school.rate_schools.average(:food) @avg5=@school.rate_schools.average(:healthcenter) @avg6=@school.rate_schools.average(:studentactivities) @avg7=@school.rate_schools.average(:facilities) @avg8=@school.rate_schools.average(:internetspeed)

codes in index : <% if !@school.rate_schools.blank? %>

library=<%=@avg1%> careercenter=<%=@avg2%> location=<%=@avg3%> Food=<%=@avg4%> Healthcenter=<%=@avg5%> studentactivities=<%=@avg6%> facilities=<%=@avg7%> internetspeed=<%=@avg8%>
      Average <%=((@avg1+@avg2+@avg3+@avg4+@avg5+@avg6+@avg7+@avg8)/8)%>
             <% end %>
        
      </tr>
        </table>

You should have a nil value to any @avg, try to use

@avgN = @school.rate_schools.average(:X) || 0

I also suggest to pass all of that logic to the model so after finding the school:

in controller

@school = School.find(params[:id])

@avg1 = @school.food_average

in model

def food_average

rate_school.average(:food)

end

Thanks a lot…it’s working…great group!