Module: CouchbaseOrm::Associations

Extended by:
ActiveSupport::Concern
Included in:
Base
Defined in:
lib/couchbase-orm/associations.rb

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#destroy_associations!Object



191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/couchbase-orm/associations.rb', line 191

def destroy_associations!
  assoc = self.class.associations
  assoc.each do |name, dependent|
    next unless dependent

    model = self.__send__(name)
    next unless model.present?

    case dependent
    when :destroy, :delete
      if model.respond_to?(:stream)
        model.stream { |mod| mod.__send__(dependent) }
      elsif model.is_a?(Array) || model.is_a?(CouchbaseOrm::ResultsProxy)
        model.each { |m| m.__send__(dependent) }
      else
        model.__send__(dependent)
      end
    when :restrict_with_exception
      raise RecordExists.new("#{self.class.name} instance maintains a restricted reference to #{name}", self)
    # when :restrict_with_error
          # TODO: :
    end
  end
end

#reset_associationsObject



216
217
218
219
220
221
222
# File 'lib/couchbase-orm/associations.rb', line 216

def reset_associations
  assoc = self.class.associations
  assoc.each do |name, _|
    instance_var = :"@__assoc_#{name}"
    remove_instance_variable(instance_var) if instance_variable_defined?(instance_var)
  end
end

#update_has_and_belongs_to_many_reverse_association(assoc, keys, is_add, **options) ⇒ Object



162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/couchbase-orm/associations.rb', line 162

def update_has_and_belongs_to_many_reverse_association(assoc, keys, is_add, **options)
  remote_method = options[:inverse_of] || self.class.to_s.pluralize.underscore.to_sym
  return if keys.empty?

  models = if options[:polymorphic]
             ::CouchbaseOrm.try_load(keys)
           else
             assoc.constantize.find(keys, quiet: true)
           end
  models = Array.wrap(models)
  models.each do |v|
    next unless v.respond_to?(remote_method)

    tab = v.__send__(remote_method) || []
    index = tab.find_index(self)
    if is_add && !index
      tab = tab.dup
      tab.push(self)
    elsif !is_add && index
      tab = tab.dup
      tab.delete_at(index)
    else
      next
    end
    v[remote_method] = tab
    v.save!
  end
end