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

前端 未结 2 1258
感动是毒
感动是毒 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:25

    There are actually two questions you are asking:

    1. How does it work?
    2. Why is it like that? (What for?)

    @arieljuod has already given you some explanations and a link.

    However the second question is still unanswered.

    There is another similar question exists which I hope will help you find all the answers:

    How can an ActiveRecord::Relation object call class methods

    It looks like the two questions (by the link and yours one) answer each other )

    Take a look at @nikita-shilnikov's answer. Good luck in your investigation!

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题