Class: ActiveRecord::Embedded::Association::One

Inherits:
ActiveRecord::Embedded::Association show all
Defined in:
lib/active_record/embedded/association/one.rb

Overview

Represents a one-to-one association between an ActiveRecord model and an ActiveRecord::Embedded::Model. Invoked by calling embeds_one on the parent model, it stores its data in the database as a Hash, which is serialized by either ActiveRecord or the database itself when persisted. As a result of this

Instance Attribute Summary

Attributes inherited from ActiveRecord::Embedded::Association

#class_name, #name

Instance Method Summary collapse

Methods inherited from ActiveRecord::Embedded::Association

#build, #embedded_class, #initialize

Constructor Details

This class inherits a constructor from ActiveRecord::Embedded::Association

Instance Method Details

#assign(model, embedded) ⇒ ActiveRecord::Embedded::Model Also known as: update

Persist the given hash or model as embedded data on this object.

Parameters:

Returns:


38
39
40
41
# File 'lib/active_record/embedded/association/one.rb', line 38

def assign(model, embedded)
  model[name] = { 'data': embedded.to_h }
  build(model, embedded)
end

#create(model, params) ⇒ Object


44
45
46
# File 'lib/active_record/embedded/association/one.rb', line 44

def create(model, params)
  build(model, params).tap(&:save)
end

#destroy(model, **_params) ⇒ Object


48
49
50
51
# File 'lib/active_record/embedded/association/one.rb', line 48

def destroy(model, **_params)
  model[name]['data'] = nil
  model[name]['data'].blank?
end

#find(model, _id = nil) ⇒ ActiveRecord::Embedded::Model

Since the #query method takes care of building the resource, ensure that the #find method signature can still work.

Parameters:

  • model (ActiveRecord::Base)
    • Parent model

Returns:


29
30
31
# File 'lib/active_record/embedded/association/one.rb', line 29

def find(model, _id = nil)
  query(model)
end

#index(_model, _indexes, _data = []) ⇒ Object


53
54
55
# File 'lib/active_record/embedded/association/one.rb', line 53

def index(_model, _indexes, _data = [])
  true
end

#query(model) ⇒ ActiveRecord::Embedded::Model

Wrap the data stored in the one-to-one relationship as an embedded model.

Parameters:

  • model (ActiveRecord::Base)
    • Parent model

Returns:


17
18
19
20
21
22
# File 'lib/active_record/embedded/association/one.rb', line 17

def query(model)
  attributes = model[name]['data']
  return if attributes.nil?

  build(model, attributes)
end