Class: ActiveRecord::Associations::Builder::SingularAssociation

Inherits:
Association show all
Defined in:
activerecord/lib/active_record/associations/builder/singular_association.rb

Overview

:nodoc:

Direct Known Subclasses

BelongsTo, HasOne

Instance Attribute Summary

Attributes inherited from Association

#name, #options, #scope

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Association

build, #build, create_builder, define_callbacks, #define_extensions, define_readers, define_writers, #initialize, #macro, valid_dependent_options, #validate_options

Constructor Details

This class inherits a constructor from ActiveRecord::Associations::Builder::Association

Class Method Details

.define_accessors(model, reflection) ⇒ Object


9
10
11
12
# File 'activerecord/lib/active_record/associations/builder/singular_association.rb', line 9

def self.define_accessors(model, reflection)
  super
  define_constructors(model.generated_association_methods, reflection.name) if reflection.constructable?
end

.define_constructors(mixin, name) ⇒ Object

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


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'activerecord/lib/active_record/associations/builder/singular_association.rb', line 15

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

    def create_#{name}(*args, &block)
      association(:#{name}).create(*args, &block)
    end

    def create_#{name}!(*args, &block)
      association(:#{name}).create!(*args, &block)
    end
  CODE
end

.define_validations(model, reflection) ⇒ Object


31
32
33
34
35
36
# File 'activerecord/lib/active_record/associations/builder/singular_association.rb', line 31

def self.define_validations(model, reflection)
  super
  if reflection.options[:required]
    model.validates_presence_of reflection.name
  end
end

Instance Method Details

#valid_optionsObject


5
6
7
# File 'activerecord/lib/active_record/associations/builder/singular_association.rb', line 5

def valid_options
  super + [:dependent, :primary_key, :inverse_of, :required]
end