Module: ActsAsRelatable::Relatable::ClassMethods

Defined in:
lib/acts_as_relatable/relatable.rb

Instance Method Summary collapse

Instance Method Details

#acts_as_relatable(*relatable_models) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/acts_as_relatable/relatable.rb', line 11

def acts_as_relatable(*relatable_models)
  # Create polymorphic associations
  class_attribute :relatable_types

  self.relatable_types = relatable_models.to_a.flatten.compact.map(&:to_sym) << self.to_s.underscore.to_sym

  has_many :relationships, :as => :relator, :order => "created_at desc", :class_name => "ActsAsRelatable::Relationship", :dependent => :destroy
  has_many :incoming_relationships, :as => :related, :class_name => "ActsAsRelatable::Relationship", :dependent => :destroy

  relatable_types.each do |rel|

    has_many "related_#{rel.to_s.pluralize}",
                              :through => :relationships,
                              :source => "related_#{rel.to_s}",
                              :class_name => rel.to_s.classify,
                              :conditions => { 'relationships.related_type' => rel.to_s.classify }

    has_many "relator_#{rel.to_s.pluralize}",
                            :through => :incoming_relationships,
                            :source => "relator_#{rel.to_s}",
                            :class_name => rel.to_s.classify,
                            :conditions => {'relationships.relator_type' => rel.to_s.classify}

    ActsAsRelatable::Relationship.belongs_to "relator_#{rel.to_s}".to_sym, :class_name => rel.to_s.classify, :foreign_key => :relator_id
    ActsAsRelatable::Relationship.belongs_to "related_#{rel.to_s}".to_sym, :class_name => rel.to_s.classify, :foreign_key => :related_id


  end

  include ActsAsRelatable::Relatable::InstanceMethods
  extend ActsAsRelatable::Relatable::SingletonMethods
end