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
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.