Conditional associations


/ Published in: Ruby
Save to your folder(s)

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


Copy this code and paste it in your HTML
  1. # assumes an associated Item class with a base_amount attribute
  2. # usage:
  3. # in = @asset.incoming_items
  4.  
  5. class Asset < ActiveRecord::Base
  6. has_many :items, :dependent => :destroy_all
  7. has_many :incoming_items, :class_name => 'Item', :conditions => "base_amount > 0"
  8. has_many :outgoing_items, :class_name => 'Item', :conditions => "base_amount < 0"
  9. end
  10.  
  11. # alternative using with_scope for adding more conditions
  12. # usage:
  13. # in = @asset.incoming(:all, :order => 'created_at desc', :limit => 15)
  14.  
  15. class Asset < ActiveRecord::Base
  16. has_many :items, :dependent => :destroy_all do
  17. def incoming(*args)
  18. args = [:all] if args.empty?
  19. with_scope(:find => { :conditions => 'base_amount > 0'}) { find(*args) }
  20. end
  21.  
  22. def outgoing(*args)
  23. args = [:all] if args.empty?
  24. with_scope(:find => { :conditions => 'base_amount < 0'}) { find(*args) }
  25. end
  26. end
  27. end

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.