Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
987 views
in Technique[技术] by (71.8m points)

ruby on rails - How does ActiveRecord define methods compared to attr_accessor?

ActiveRecord seems to define instance methods differently than attr_accessor.

attr_accessor doesn't 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..

Whereas 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 make attr_accessor define a super method?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

On the other hand, ActiveRecord does define a getter and a setter for your attributes. Therefore, when you define them again in your class (that inherits from ActiveRecord::Base), then Ruby has somewhere to go (ActiveRecord::Base) when you invoke super.

Contrasting attr_accessor and the (many) methods that ActiveRecord generates for your table columns is a bit of an apples and oranges kind of question. ActiveRecord does all sorts of things with the attributes on the underlying table, including--but not limited to--creating getters and setters for the table columns.

(Note on the above: ActiveRecord works mostly by harnessing the power of method_missing, so many or most of the methods defined on your table attributes are actually implemented through the method_missing method. super does in fact invoke method_missing, if it exists, in parent classes, so that is how you can successfully invoke super on some_attribute when you inherit from ActiveRecord::Base.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...