how does this Ruby class method get invoked?

前端 未结 2 2014
后悔当初
后悔当初 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:18

    This is just one of the things Rails does. Any class methods automatically become available as "collection" methods, meaning they are available to the relation objects. Scopes and class methods are interchangeable that way.

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

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