Module: ToyAttributes::Relations

Defined in:
lib/toy-attributes/relations.rb

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



3
4
5
6
7
8
9
10
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
43
44
45
46
# File 'lib/toy-attributes/relations.rb', line 3

def self.included base
  base.instance_eval do

    alias :_has_many :has_many
    alias :_has_one :has_one

    def has_many *models
      has :many, *models
    end

    def has_one *models
      has :one, *models
    end

    private

    def has quantity, *models
      options = models.extract_options!
      models.each do |model|
        self.send :"_has_#{quantity}", model, options
        enforce_relation_with model, options
      end
    end

    def enforce_relation_with model, options
      if options[:class_name]
        related = options[:class_name].constantize
        related.integer options[:foreign_key]
        symbol = options[:foreign_key].to_s[0..-4].to_sym
        related.belongs_to symbol, class_name: to_s
        accepts_nested_attributes_for model
        attr_accessible :"#{model}_attributes"
      else
        related = model.to_s.singularize.classify.constantize
        symbol = to_s.underscore.to_sym
        related.integer :"#{symbol}_id"
        related.belongs_to symbol
        accepts_nested_attributes_for model
        attr_accessible :"#{model}_attributes"
      end
    end

  end
end