class NoBrainer::Document::Association::BelongsTo

Public Instance Methods

after_validation_callback() click to toggle source
# File lib/no_brainer/document/association/belongs_to.rb, line 184
def after_validation_callback
  if loaded? && target && !target.persisted? && target != owner
    raise NoBrainer::Error::AssociationNotPersisted.new("#{target_name} must be saved first")
  end
end
assign_foreign_key(value) click to toggle source

Note: @target_container is an array to distinguish the following cases:

  • target is not loaded, but perhaps present in the db.

  • we already tried to load target, but it wasn’t present in the db.

# File lib/no_brainer/document/association/belongs_to.rb, line 136
def assign_foreign_key(value)
  @target_container = nil
end
loaded?() click to toggle source
# File lib/no_brainer/document/association/belongs_to.rb, line 180
def loaded?
  !@target_container.nil?
end
polymorphic_read() click to toggle source
# File lib/no_brainer/document/association/belongs_to.rb, line 140
def polymorphic_read
  return target if loaded?

  target_class = owner.read_attribute(foreign_type)
  fk = owner.read_attribute(foreign_key)

  if target_class && fk
    preload(base_criteria(target_class).where(primary_key => fk).first)
  end
end
polymorphic_write(target) click to toggle source
# File lib/no_brainer/document/association/belongs_to.rb, line 159
def polymorphic_write(target)
  owner.write_attribute(foreign_key, target.try(primary_key))
  owner.write_attribute(foreign_type, target.root_class.name)
  preload(target)
end
preload(targets) click to toggle source
# File lib/no_brainer/document/association/belongs_to.rb, line 171
def preload(targets)
  @target_container = [*targets] # the * is for the generic eager loading code
  target
end
read() click to toggle source
# File lib/no_brainer/document/association/belongs_to.rb, line 151
def read
  return target if loaded?

  if fk = owner.read_attribute(foreign_key)
    preload(base_criteria.where(primary_key => fk).first)
  end
end
target() click to toggle source
# File lib/no_brainer/document/association/belongs_to.rb, line 176
def target
  @target_container.first
end
write(target) click to toggle source
# File lib/no_brainer/document/association/belongs_to.rb, line 165
def write(target)
  assert_target_type(target)
  owner.write_attribute(foreign_key, target.try(primary_key))
  preload(target)
end