class NinjaModel::Associations::HasOneAssociation

Public Instance Methods

delete(method = options[:dependent]) click to toggle source
# File lib/ninja_model/associations/has_one_association.rb, line 28
def delete(method = options[:dependent])
  if load_target
    case method
    when :delete
      target.delete
    when :destroy
      target.destroy
    when :nullify
      target.update_attribute(reflection.foreign_key, nil)
    end
  end
end
replace(record, save = true) click to toggle source
# File lib/ninja_model/associations/has_one_association.rb, line 5
def replace(record, save = true)
  raise_on_type_mismatch(record) if record
  load_target

  if target && target != record
    remove_target!(options[:dependent]) unless target.destroyed?
  end

  if record
    set_owner_attributes(record)
    set_inverse_instance(record)

    if owner.persisted? && save && !record.save
      nullify_owner_attributes(record)
      set_owner_attributes(target) if target
      raise RecordNotSaved, "Failed to save the new associated #{reflection.name}."
    end
  end

  self.target = record

end

Private Instance Methods

nullify_owner_attributes(record) click to toggle source
# File lib/ninja_model/associations/has_one_association.rb, line 60
def nullify_owner_attributes(record)
  record[reflection.foreign_key] = nil
end
remove_target!(method) click to toggle source
# File lib/ninja_model/associations/has_one_association.rb, line 47
def remove_target!(method)
  if method.in?([:delete, :destroy])
    target.send(method)
  else
    nullify_owner_attributes(target)

    if target.persisted? && owner.persisted? && !target.save
      set_owner_attributes(target)
      raise RecordNotSaved, "Failed to remove the existing associated #{reflection.name}.  The record failed to save when after its foreign key was set to nil."
    end
  end
end
set_new_record(record) click to toggle source
# File lib/ninja_model/associations/has_one_association.rb, line 43
def set_new_record(record)
  replace(record, false)
end