I am having trouble 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
Generate the following error:
test.rb:4:in 'testar': undefined method '+' for nil:NilClass (NoMethodError)
from test.rb:9:in '<main>'
Because @test
has not been initialized, so I see that it does not work to initialize this in the body of the class, is there a more elegant way of doing this than using after_initialize
? As in the example below:
def after_initialize
@test = 1
end