how does this Ruby class method get invoked?

前端 未结 2 2020
后悔当初
后悔当初 2020-12-18 10:53

In a screen cast on Exporting CSV from a rails app, Ryan Bates presented the following simple code.

I\'m trying to figure out how the class method Product::to_csv ac

2条回答
  •  既然无缘
    2020-12-18 11:34

    I can answer the following question for now:

    Why do messages sent to an instance of ActiveRecord::Relation cause methods on the Product class object to get invoked?

    ActiveRecord::Relation class is used to chain several methods without actually trigger multiple SQL queries. This way you can write something like Product.where('price <= ?', 100).order(:price).limit(30) and Rails will execute just one query.

    The magic works because you have an ActiveRecord::Relation instance until you try to access the data (e.g. because a first or all call), at that time the query will be run and you'll have ActiveRecord::Base or one of his descendants.

    Long story short, if you check the class with @products.class you'll see is an ActiveRecord::Relation but later you have Product instances, and then you can call the to_csv method.

提交回复
热议问题