How do rails association methods work?

后端 未结 4 632
自闭症患者
自闭症患者 2020-11-29 04:29

How do rails association methods work? Lets consider this example

class User < ActiveRecord::Base
   has_many :articles
end

class Article < ActiveReco         


        
4条回答
  •  野性不改
    2020-11-29 04:34

    As metioned previously, when doing

    @user.articles.class
    => Array
    

    what you actually get is Array. That is because #class method was undefined, as also mentioned before.

    But how do you get the actual class of @user.articles (which should be proxy)?

    Object.instance_method(:class).bind(@user.articles).call
    => ActiveRecord::Associations::CollectionProxy
    

    And why did you get Array in the first place? Because #class method was delegated to CollectionProxy @target instance through method missin, which is actually an array. You could peek behind the scene by doing something like this:

    @user.articles.proxy_association
    

提交回复
热议问题