I was confused about the different ways to access instance variables in rails models. For example, this will work:
def add_calories(ingredient)
self.total_calories += ingredient.calories
p total_calories
end
However this will results in errors:
def add_calories(ingredient)
total_calories += ingredient.calories
end
Error: NoMethodError: undefined method "+" for nil:NilClass
Also this won't work either.
def add_calories(ingredient)
total_calories = total_calories + ingredient.calories
end
If I can access the instance variable without self in the first case, how come that in the second case, total_calories becomes nil?
Could it be that the default value for total_calories is set to 0? However if that's the case, why does self.total_calories work?
t.integer "total_calories", default: 0
I read this post but it doesn't really explain why the third case won't work.
Thanks a lot.