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?
self.x/self.x=yare always method calls.(
self.xis just sugar forself.__send__(:x)andself.x = yis really just sugar forself.__send__(:x=, y))@x, on the other hand, only refers to an instance variable.Using
@xwill not work with AR associations as AR only definesx/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_accessorallows “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 thatattr_accessor :xis equivalent to:Happy coding.