Class: DuckRecord::Associations::Builder::BelongsTo

Inherits:
SingularAssociation show all
Defined in:
lib/duck_record/associations/builder/belongs_to.rb

Overview

:nodoc:

Constant Summary

Constants inherited from Association

Association::VALID_OPTIONS

Class Method Summary collapse

Methods inherited from SingularAssociation

define_constructors

Methods inherited from Association

build, build_scope, create_reflection, define_extensions, define_readers, define_writers, validate_options, wrap_scope

Class Method Details

.add_default_callbacks(model, reflection) ⇒ Object



20
21
22
23
24
# File 'lib/duck_record/associations/builder/belongs_to.rb', line 20

def self.add_default_callbacks(model, reflection)
  model.before_validation lambda { |o|
    o.association(reflection.name).default(&reflection.options[:default])
  }
end

.define_accessors(mixin, reflection) ⇒ Object



16
17
18
# File 'lib/duck_record/associations/builder/belongs_to.rb', line 16

def self.define_accessors(mixin, reflection)
  super
end

.define_callbacks(model, reflection) ⇒ Object



11
12
13
14
# File 'lib/duck_record/associations/builder/belongs_to.rb', line 11

def self.define_callbacks(model, reflection)
  super
  add_default_callbacks(model, reflection) if reflection.options[:default]
end

.define_validations(model, reflection) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/duck_record/associations/builder/belongs_to.rb', line 26

def self.define_validations(model, reflection)
  if reflection.options.key?(:required)
    reflection.options[:optional] = !reflection.options.delete(:required)
  end

  if reflection.options[:optional].nil?
    required = true
  else
    required = !reflection.options[:optional]
  end

  super

  if required
    model.validates_presence_of reflection.name, message: :required
  end
end

.macroObject



3
4
5
# File 'lib/duck_record/associations/builder/belongs_to.rb', line 3

def self.macro
  :belongs_to
end

.valid_options(_options) ⇒ Object



7
8
9
# File 'lib/duck_record/associations/builder/belongs_to.rb', line 7

def self.valid_options(_options)
  super + [:optional, :default]
end