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

Constant Summary

Constants inherited from Association

Association::VALID_OPTIONS

Class Method Summary collapse

Methods inherited from Association

add_destroy_callbacks, build, build_scope, check_dependent_options, create_reflection, define_callbacks, define_extensions, define_readers, define_validations, define_writers, macro, valid_dependent_options, validate_options, wrap_scope

Class Method Details

.define_accessors(model, reflection) ⇒ Object


9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'activerecord/lib/active_record/associations/builder/singular_association.rb', line 9

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

  define_constructors(mixin, name) if reflection.constructable?

  mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
    def reload_#{name}
      association(:#{name}).force_reload_reader
    end
  CODE
end

.define_constructors(mixin, name) ⇒ Object

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


24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'activerecord/lib/active_record/associations/builder/singular_association.rb', line 24

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

.valid_options(options) ⇒ Object


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

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