I have recently come upon an error when I added the following to my environment.rb file:
class Array
def sum
self.inject{|sum,x| sum + x }
end
end
The intended method, which allows me to do array.sum, works perfectly, but it has caused a strange error when I try to access objects via a given objects has_many relationship, for example:
class Device < ActiveRecord::Base
attr_accessible :name, :device_abilities, :abilities
has_many :device_abilities, :dependent => :destroy
has_many :abilities, :through => :device_abilities, :dependent => :destroy
end
class Ability < ActiveRecord::Base
attr_accessible :name, :device_abilities, :devices
has_many :device_abilities, :dependent => :destroy
has_many :devices, :through => :device_abilities, :dependent => :destroy
end
class DeviceAbility < ActiveRecord::Base
attr_accessible :device_id, :ability_id
belongs_to :device
belongs_to :ability
end
This works fine without the sum method in environment.rb, so I can do @device.abilities as normal, but when the sum method is added in environment.rb, i get the following error when trying to do @device.abilities:
undefined method `zero?' for nil:NilClass
Can anyone suggest why this is happening, and how I can work around it? I know that i can sum each array manually, but this doesn’t seem very rails-esque.
Thanks!
sum is already defined by rails as Enumerable#sum, so you shouldn’t have to define it at all.
Also, I don’t think environment.rb is the right place to put this sort of thing. You should create a new initializer file if you want to extend base classes. Your new method is probably interfering with rails’ version of it.