Module ActiveRecord::Extensions::FindToCSV
In: lib/ar-extensions/csv.rb

Adds CSV export options to ActiveRecord::Base models.

Example 1, exporting all fields

 class Book < ActiveRecord::Base ; end

 book = Book.find( 1 )
 book.to_csv

Example 2, only exporting certain fields

 class Book < ActiveRecord::Base ; end

 book = Book.find( 1 )
 book.to_csv( :only=>%W( title isbn )

Example 3, exporting a model including a belongs_to association

 class Book < ActiveRecord::Base
   belongs_to :author
 end

 book = Book.find( 1 )
 book.to_csv( :include=>:author )

This also works for a has_one relationship. The :include option can also be an array of has_one/belongs_to associations. This by default includes all fields on the belongs_to association.

Example 4, exporting a model including a has_many association

 class Book < ActiveRecord::Base
   has_many :tags
 end

 book = Book.find( 1 )
 book.to_csv( :include=>:tags )

This by default includes all fields on the has_many assocaition. This can also be an array of multiple has_many relationships. The array can be mixed with has_one/belongs_to associations array as well. IE: :include=>[ :author, :sales ]

Example 5, nesting associations

 class Book < ActiveRecord::Base
   belongs_to :author
   has_many :tags
 end

 book = Book.find( 1 )
 book.to_csv( :includes=>{
                 :author => { :only=>%W( name ) },
                 :tags => { :only=>%W( tagname ) } )

Each included association can receive an options Hash. This allows you to nest the associations as deep as you want for your CSV export.

It is not recommended to nest multiple has_many associations, although nesting multiple has_one/belongs_to associations.

Classes and Modules

Module ActiveRecord::Extensions::FindToCSV::InstanceMethods

Constants

ALIAS_FOR_FIND = :_original_find_before_arext

[Validate]