CollectionProxy vs AssociationRelation

后端 未结 2 905
长情又很酷
长情又很酷 2021-01-01 18:54

I am wondering about the difference between ActiveRecord::Associations::CollectionProxy and ActiveRecord::AssociationRelation.

clas         


        
2条回答
  •  太阳男子
    2021-01-01 19:23

    Ok. The difference is pretty simple.

    Explanation based on your example:

    the association proxy in v.wheels has:

    • the object in v as @owner;
    • the collection of its wheels as @target;
    • and the @reflection object represents a :has_many macro.

    From docs:

    Association proxies in Active Record are middlemen between the @owner and the @target. The @target object is not loaded until needed.

    v = Vehicle.new
    v.wheels # we are not sending any methods to @target object (collection of wheels)
    # => #
    

    Which means, as soon as you call any method on the @target object (that holds collection of wheels in our case) the @target is loaded, and it becomes ActiveRecord_AssociationRelation.

    v.wheels.all # sending the `all` method to @target (wheels)
    # => #
    

提交回复
热议问题