Method: DataActive::Entity#update_associations

Defined in:
lib/data_active/entity.rb

#update_associationsObject



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/data_active/entity.rb', line 67

def update_associations
  if belongs_to.present? and not belongs_to.excluded
    association = belongs_to.klass.reflect_on_all_associations.select { |a| a.plural_name == @klass.name.underscore.pluralize }[0]
    if belongs_to.record.new_record?
      existing = belongs_to.find_existing
      belongs_to.record = existing if existing.present?
    end

    if belongs_to.record.new_record?
      case association.macro
        when :has_many, :has_many_and_blongs_to
          belongs_to.record.__send__(association.name) << @record

        when :has_one
          belongs_to.record.__send__("#{association.name}=", @record)

        else
          raise "unsupported association #{association.macro} for #{association.name} on #{@klass.name}"

      end
    else
      foreign_key = foreign_key_from(association)
      @record.__send__("#{foreign_key}=", belongs_to.record.__send__(belongs_to.klass.primary_key.to_sym))
    end
  end
end