Class: NoBrainer::Document::Association::BelongsTo

Inherits:
Object
  • Object
show all
Includes:
Core
Defined in:
lib/no_brainer/document/association/belongs_to.rb

Defined Under Namespace

Classes: Metadata

Instance Method Summary collapse

Methods included from Core

#assert_target_type, #initialize

Instance Method Details

#after_validation_callbackObject



184
185
186
187
188
# 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) ⇒ Object

Note:

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

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



136
137
138
# File 'lib/no_brainer/document/association/belongs_to.rb', line 136

def assign_foreign_key(value)
  @target_container = nil
end

#loaded?Boolean

Returns:



180
181
182
# File 'lib/no_brainer/document/association/belongs_to.rb', line 180

def loaded?
  !@target_container.nil?
end

#polymorphic_readObject



140
141
142
143
144
145
146
147
148
149
# 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) ⇒ Object



159
160
161
162
163
# 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) ⇒ Object



171
172
173
174
# 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

#readObject



151
152
153
154
155
156
157
# 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

#targetObject



176
177
178
# File 'lib/no_brainer/document/association/belongs_to.rb', line 176

def target
  @target_container.first
end

#write(target) ⇒ Object



165
166
167
168
169
# 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