Report abuse

phase 1


			
# original code from TheRailsWay example
class Item < ActiveRecord::Base
  belongs_to :asset
end

class Asset < ActiveRecord::Base
  # all items, incoming and outgoing
  has_many :items, :dependent => :destroy_all do
    def incoming
      @incoming ||= find(:all, :conditions => "base_amount > 0")
    end

    def outgoing
      @outgoing ||= find(:all, :conditions => "base_amount < 0")
    end
  end
end

phase 2


			
# Lets you do this:
#
#   @asset.items.incoming(:all, :order => 'created_at desc', :limit => 15)
class Asset < ActiveRecord::Base
  # all items, incoming and outgoing
  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

phase 3


			
# Now the incoming/outgoing methods are on item, so you can do:
#
#   Item.incoming(:all, :order => 'created_at desc', :limit => 15)
#
# or
#   
#   @asset.items.incoming(:all, :order => 'created_at desc', :limit => 15)
class Item < ActiveRecord::Base
  belongs_to :asset
  def self.incoming(*args)
    with_scope(:find => { :conditions => 'base_amount > 0'}) { find(*args) }
  end

  def self.outgoing(*args)
    with_scope(:find => { :conditions => 'base_amount < 0'}) { find(*args) }
  end
end

class Asset < ActiveRecord::Base
  has_many :items, :dependent => :destroy_all
end