How does ActiveRecord::Relation get added to Rails' models and why does each model have individual Relation class?

前端 未结 2 1261
感动是毒
感动是毒 2021-01-25 05:13

Suppose I have a Rails model: class Project < ActiveRecord::Base

In the Rails console:

> Project.all
=> #

        
2条回答
  •  感情败类
    2021-01-25 05:28

    Check this line of code from ActiveRecord.

    https://github.com/rails/rails/blob/f40860800c231ecd1daef6cf6b5a8a8eda76478d/activerecord/lib/active_record/relation/delegation.rb#L23

    mangled_name = klass.name.gsub("::", "_")
    

    So, for your questions:

    • it get's added on activerecord's base when it extendes the delegation module https://github.com/rails/rails/blob/f40860800c231ecd1daef6cf6b5a8a8eda76478d/activerecord/lib/active_record/base.rb#L290

    • it's actually the same class, just something like an alias (not actually an alias, it's a constant with the class as value)

    • the class is actually an ActiveRecord::Relation, it's just that the name was changed

提交回复
热议问题