Module: ActiveRecord::Extensions::FindToCSV

Defined in:
lib/ar-extensions/csv.rb

Overview

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.

Defined Under Namespace

Modules: ArrayInstanceMethods, ClassMethods, InstanceMethods Classes: FieldMap

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
# File 'lib/ar-extensions/csv.rb', line 70

def self.included(base)
  if !base.respond_to?(:find_with_csv)
    base.class_eval do
      extend ClassMethods
      include InstanceMethods        
    end
    class << base
      alias_method_chain :find, :csv
    end
  end
end