I am analysing the rails source code, because I wold like to understand the inner workings of the has_many
and similar constructs.
So far, I was able to find where the method is implemented (link to github): it is in the module ActiveRecord::Associations
def has_many(name, options = {}, &extension)
Builder::HasMany.build(self, name, options, &extension)
end
This one eventualy ends (link to github) in the class ActiveRecord::Associations::Builder::CollectionAssociation as
def self.build(model, name, options, &extension)
new(model, name, options, &extension).build
end
There is where my ruby skills end and I could not track it further and find where is "new" implemented and what it does.
Can someone point me to the right direction and maybe comment along, what is going on under the hood?
Rails offers two different ways to declare a many-to-many relationship between models. The first way is to use has_and_belongs_to_many, which allows you to make the association directly: The second way to declare a many-to-many relationship is to use has_many :through.
A has_many association is similar to has_one , but indicates a one-to-many connection with another model. You'll often find this association on the "other side" of a belongs_to association. This association indicates that each instance of the model has zero or more instances of another model.
Basically, new
is defined like this:
class Class
def new(*args, &block)
obj = allocate
obj.initialize(*args, &block)
# *actually* obj.send(:initialize, *args, &block) since initialize is private
obj
end
end
allocate
is defined like this:
class Class
def allocate
# magic stuff for creating an empty object which cannot be expressed in Ruby:
new_obj = Deep::Within::VM.__somehow_magically_allocate_memory__!
new_obj.__class__ = self
new_obj
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With