While doing a bit of work on Tempo recently, we found we had the need to provide a union’ed set of Active Record associations on a model. We already had the code in place in acts_as_network to do something very similar via the UnionCollection class, so it was a simple step to create ActsAsUnion within the same plugin.
Here’s an example of what we mean and how it works:
class Person < ActiveRecord::Base
acts_as_network :colleagues, :through => :invites, :foreign_key => 'person_id',
:conditions => ["is_accepted = 't'"]
acts_as_union :aquantainces, [:friends, :colleagues]
In this case a call to the aquantainces method will return a UnionCollection on both a person’s friends and their colleagues. Likewise, finder operations will work accross the two distinct sets as if they were one. Thus, for the following code:
stephen = Person.find_by_name('Stephen')
# search for user by login
billy = stephen.aquantainces.find_by_name('Billy')
both Stephen’s friends and colleagues collections would be searched for someone named Billy.
To obtain acts_as_union, simple install the newest version of the acts_as_network plugin and use as shown above. The acts_as_union method does not accept any options.