how Differences between *, self.* and @* when referencing associations/attributes in Ruby/Rails Models/Controllers

 

Questions


Assuming a Rails Model with persistent / non-persistent attributes, what is the best practice regarding referencing them? If you look at code publicly available, different patterns are used.

For instance, if you have an association from one model to another. What is the difference between using self.association_name and @association_name?. What is the preferable way?

Same as with non-persistent attributes defined with attr_accessor :attr in Models. You can reference them with both approaches, self.attr and @attr. What is the preferable way?

 

 

————————————————-

Answer

self.x/self.x=y are always method calls.

(self.x is just sugar for self.__send__(:x) and self.x = y is really just sugar for self.__send__(:x=, y))

@x, on the other hand, only refers to an instance variable.

Using @x will not work with AR associations as AR only defines x/x= (which are methods) for its magical operation. (AR essentially just “captures” intent access through these methods and routes through its own internal data structures which are unrelated to any similar-named instance variables.)

attr_accessor allows “accessing both ways” because and only because it uses the same-named instance variable as it’s backing (it has to store the value somewhere). Consider that attr_accessor :x is equivalent to:

def x; @x; end
def x= (y); @x = y; end

Happy coding.

ruby,ruby-on-rails

Facebook Comments

Post a comment