using Has_many_polymorphs

So I needed to establish a relation between one model and many other models, the User model can own many other models like Restaurants and Cafes, has_many_polymorphs comes to the rescue, check the plugin homepage for installation details.

Here are my models

class User < ActiveRecord::Base
  acts_as_authentic
  has_many_polymorphs :entities, :from => [:restaurants, :travel_agencies]
end

class EntitiesUser < ActiveRecord::Base
 belongs_to :user
 belongs_to :entity, :polymorphic => true
end

following is the migration for the EntitiesUser model

class CreateEntitiesUsers < ActiveRecord::Migration
 def self.up
   create_table :entities_users do |t|
     t.references :entity, :polymorphic => true
     t.references :user
     t.timestamps
   end
 end

 def self.down
   drop_table :entities_users
 end
end

And to make sure the links between the two models are being established I used the following code in the Entity model

  after_create :add_entity_user
  after_destroy :delete_entity_user

  protected
  def add_entity_user #add a relation between the entity and the currently logged in user
    user = UserSession.find.record
    eu = EntitiesUser.new( :entity_id => self.id, :entity_type => self.class.name, :user_id => user.id  )
    eu.save
  end
  def delete_entity_user #delete the relations for this entity
    eus = EntitiesUser.find(:all, :conditions => ["entity_id = ? and entity_type = ?", self.id, self.class.name])
    eus.each { |e| e.destroy }
  end

hope this helps.

Leave a comment