When should self be used in a Model in Rails?

3

Within a Model , when I have a variable write operation in a method, why do I need to add self to work correctly?

For example, if I have the following code:

class Zombie < ActiveRecord::Base
  beffore_save :make_rotting

  def make_rotting
    if age > 20
        self.rotting = true
    end    
  end

end

On the other hand, if I omit the self, it does not work:

class Zombie < ActiveRecord::Base
  beffore_save :make_rotting

  def make_rotting
    if age > 20
        rotting = true  #No funciona correctamente
    end    
  end

end

Note : variable age reads it without any problem in both cases.

Why is there a difference in the behavior of rotting with the presence of self , while in age does not change?

    
asked by Alejandro Montilla 25.01.2017 в 19:54
source

1 answer

3

When you make rotting = true , what you are doing is declaring a local variable that works in the scope of the make_rotting method and will disappear when the execution of the method ends.
Now, when you call self.rotting = true , you are asking to modify the rotting attribute of your current instance of zombie , which is how it should be done.

In general, in an instance method of a model, you should use self when modifying attributes or when there is some ambiguity between calling a local variable and an already defined attribute / method, for example:

  def make_rotting(age)
    if (age || self.age) > 20
        self.rotting = true
    end    
  end

The first call to age refers to the local variable that comes as a method parameter, while the second one ( self.age ) refers to the attribute, without necessarily modifying this attribute.

Regarding why it is the same to call age or self.age if the case is just read an attribute, it is in the order in which ruby tries to solve the call to age :

  • First check in the field of make_rotting if there is any variable age defined.
  • If you can not find it, it will search within the scope of the instance of zombie if age is defined.

In case of using self.age , you are explicitly indicating that you look for the definition in the instance of zombie .

    
answered by 25.01.2017 / 22:15
source