Class: DuckRecord::Associations::Builder::SingularAssociation

Inherits:
Association
  • Object
show all
Defined in:
lib/duck_record/associations/builder/singular_association.rb

Overview

:nodoc:

Direct Known Subclasses

BelongsTo, EmbedsOne, HasOne

Constant Summary

Constants inherited from Association

Association::VALID_OPTIONS

Class Method Summary collapse

Methods inherited from Association

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

Class Method Details

.define_accessors(model, reflection) ⇒ Object



16
17
18
19
20
21
22
# File 'lib/duck_record/associations/builder/singular_association.rb', line 16

def self.define_accessors(model, reflection)
  super
  mixin = model.generated_association_methods
  name = reflection.name

  define_constructors(mixin, name) if reflection.constructable?
end

.define_constructors(mixin, name) ⇒ Object

Defines the (build|create)_association methods for belongs_to or has_one association



25
26
27
28
29
30
31
# File 'lib/duck_record/associations/builder/singular_association.rb', line 25

def self.define_constructors(mixin, name)
  mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
    def build_#{name}(*args, &block)
      association(:#{name}).build(*args, &block)
    end
  CODE
end

.define_validations(model, reflection) ⇒ Object



8
9
10
11
12
13
14
# File 'lib/duck_record/associations/builder/singular_association.rb', line 8

def self.define_validations(model, reflection)
  super

  if reflection.options[:required]
    model.validates_presence_of reflection.name, message: :required
  end
end

.valid_options(options) ⇒ Object

:nodoc:



4
5
6
# File 'lib/duck_record/associations/builder/singular_association.rb', line 4

def self.valid_options(options)
  super + [:primary_key, :required]
end