ActiveRecord: why self. instead of @ to access column values in a Model?
I'm confused why column values for a record cannot be accessed using @column_name. Why are they not instance variables? How is activerecord holding their value? Why is it necessary to prefix the column name with 'self.' for assignment?
T开发者_运维技巧hank you for clarifying this mystery for me!
because if you mistype @f00 its a pain to figure out why your code isn't working when you meant @foo or @Foo. This way there will be a "no method error" on a typo instead of making a new variable you didn't want
Edit
I misread the question. I thought you meant about inside the ActiveRecord source when they do that. The real reason is because ActiveRecord is implemented almost entirely through reflection. It checks the database for column_names and then dynamically makes setters and getters for those fields via method_missing. If I recall correctly after you use the self.field it sets @field. This might be hidden somewhere like in @attributes[:field].
精彩评论