Return to Snippet

Revision: 2365
at February 4, 2007 15:12 by gnatware


Updated Code
# 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

Revision: 2364
at February 4, 2007 15:07 by gnatware


Initial Code
# assumes an associated Item class with a base_amount attribute

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

Initial URL
http://www.therailsway.com/2007/1/8/assetsgraphed-part-1

Initial Description
Define multiple associations on the same associated class.  From the Rails Way blog.

Initial Title
Conditional associations

Initial Tags
rails

Initial Language
Ruby