Initialization of instance variables in ActiveRecord

2

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
    
asked by anonymous 19.11.2014 / 14:47

2 answers

1

As far as I know, there is no other way to recommend it, except using after_initialize .

The original% of the class may not be invoked in some cases by ActiveRecord, then. initialize was created just to solve the boot problem.

There is a discussion on all this in this OS issue and in this article . See also documentation explaining after_initialize .

    
19.11.2014 / 15:40
0

The way you did, assigning @test = 1 within the class, you are setting a class variable and not an instance variable.

To do what you want, you can use the ||= operator. If you use the variable in more than one location, I suggest accessing it via a read method.

class Test < ActiveRecord::Base
  def test
    @test ||= 1
  end

  def testar
    test + 1
  end
end

t = Test.new
t.testar # => 2

The @test ||= 1 operator works as if it were @test = @test || 1 . The first time you call the test method, the @test variable is nil, so it assigns 1 to @test (and returns that value). In the next calls, as @test is already set, the method only returns the value of the variable.

    
20.11.2014 / 22:12