Initializing instance variables in Activerecord

Asked

Viewed 624 times

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

2 answers

1


0

The way you did, assigning @test = 1 within the class, you are defining 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 through a reading method.

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

  def testar
    test + 1
  end
end

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

The operator @test ||= 1 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 this value). In the next calls, as @test is already defined, the method only returns the variable value.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.