/ Published in: Ruby
                    
                                        
Define multiple associations on the same associated class.  From the Rails Way blog.
                
                            
                                Expand |
                                Embed | Plain Text
                            
                        
                        Copy this code and paste it in your HTML
# assumes an associated Item class with a base_amount attribute
# usage:
# in = @asset.incoming_items
class Asset < ActiveRecord::Base
has_many :items, :dependent => :destroy_all
has_many :incoming_items, :class_name => 'Item', :conditions => "base_amount > 0"
has_many :outgoing_items, :class_name => 'Item', :conditions => "base_amount < 0"
end
# alternative using with_scope for adding more conditions
# usage:
# in = @asset.incoming(:all, :order => 'created_at desc', :limit => 15)
class Asset < ActiveRecord::Base
has_many :items, :dependent => :destroy_all do
def incoming(*args)
args = [:all] if args.empty?
with_scope(:find => { :conditions => 'base_amount > 0'}) { find(*args) }
end
def outgoing(*args)
args = [:all] if args.empty?
with_scope(:find => { :conditions => 'base_amount < 0'}) { find(*args) }
end
end
end
URL: http://www.therailsway.com/2007/1/8/assetsgraphed-part-1
Comments
 Subscribe to comments
                    Subscribe to comments
                
                