2
I’m having difficulty initializing instance variables in Rails, I need to use a variable in several methods, but this needs to be initialized beforehand, for example:
class Test < ActiveRecord::Base
@test = 1
def testar
@test+1
end
end
t = Test.new
t.testar
Generates the following error:
test.rb:4:in `testar': undefined method `+' for nil:NilClass (NoMethodError)
from test.rb:9:in `<main>'
For @test
has not been initialized, so I see that it does not work to perform this initialization in the class body, there is a more elegant way to do this than you use after_initialize
? As in the example below:
def after_initialize
@test = 1
end