How does ActiveRecord define methods compared to attr_accessor?

ActiveRecord seems to define instance methods differently than attr_accessor.

attr_accessor does not seem to define a super method for my new defined attribute:

class SomeClass attr_accessor :some_attribute def some_attribute super end end >> some_class = SomeClass.new >> some_class.some_attribute NoMethodError: super: no superclass method `some_attribute' for.. 

While ActiveRecord definitely defines a super method :

 class SomeClass < ActiveRecord::Base # some_attribute is now a column in our database def some_attribute super end end >> some_class = SomeClass.new >> some_class.some_attribute nil 

Where is the difference between both? Is there a way to get attr_accessor to define a super method?

EDIT: I still don't know how ActiveRecord defines its methods, but I know how attr_accessor does it. Instead of super I can use @some_attribute , since it saves the values ​​in global variables with the same name: https://stackoverflow.com/a/316629/

+6
source share
1 answer

When you use attr_accessor in your class that does not inherit from another class, by definition there is no method with the same name in the "parent" class. Therefore, there is nowhere to look super to find the same type of method. (Well, your class inherits from Object, but Object does not define a method called some_attribute.)

ActiveRecord, on the other hand, defines a getter and setter for your attributes. Therefore, when you define them again in your class (which inherits from ActiveRecord :: Base), then Ruby must go somewhere (ActiveRecord :: Base) when calling super.

The contrast of attr_accessor and the (many) methods that ActiveRecord generates for your table columns is a bit of a question about apples and oranges. ActiveRecord performs all sorts of actions with attributes in the base table, including (but not limited to) creating getters and setters for table columns.

(Note the above: ActiveRecord works mainly by using the method_missing method, so many or most of the methods defined in your table attributes are actually implemented using the method_missing method. Super really calls the method_missing method, if it exists, in the parent classes, so that you can successfully call super on some_attribute when inheriting from ActiveRecord :: Base.)

+11
source

All Articles