0

This is driving me nuts with loads of undeclared variables. I have created a simple scaffold with text and integers. How to sum up all integers? See image:

enter image description here

I only want to sum up the "Watts". Im using Rails 4; Ruby 2.1.3

I get this: undefined method 'all' for nil:NilClass" when I put this code in my app/models/bathroom_accessory.rb:

def total
 @bathroom_accessory.all.sum(&:watts)
end

Have I done something wrong?

Sylar
  • 11,422
  • 25
  • 93
  • 166

2 Answers2

1

You've tried to refer to an instance variable rather than the collection of all accessories:

def total
  BathroomAccessory.all.sum(&:watts)
end
David Hoelzer
  • 15,862
  • 4
  • 48
  • 67
1

Another way to do this (without the all):

 def total
   BathroomAccessory.sum(:watts)
 end

For the sake of the question, is important for the OP to understand this call:

@bathroom_accessory.all.sum(&:watts)

Is incorrect since sum is defined at a class level and @bathroom_accessory is declared as an instance variable. Even this code is incorrect:

 def total
   @bathroom_accessory = BathroomAccessory.new
   @bathroom_accessory.sum(:watts)
 end

This last code will raise a NoMethodError error.

Hernan Velasquez
  • 2,770
  • 14
  • 21