I want to export a csv file from Rails and I'm following the Railscast on this topic (http://railscasts.com/episodes/362-exporting-csv-and-excel?view=asciicast).
In the Railscast, the controller (products_controller.rb) contains:
def index
@products = Product.order(:name)
respond_to do |format|
format.html
format.csv { send_data @products.to_csv }
end
end
The Product model (models/product.rb) contains:
def self.to_csv
CSV.generate do |csv|
csv << column_names
all.each do |product|
csv << product.attributes.values_at(*column_names)
end
end
end
As seen in this StackOverflow question (Exporting CSV data from Rails), to_csv is a class method that is being called on an array of class objects. I expected this to fail because to_csv is not being called on the Product class.
This works, but why does it work?
Product.to_csv(@products)instead of@products.to_csvin the controller.