Class: Ooor::Reflection::AssociationReflection

Inherits:
MacroReflection show all
Defined in:
lib/ooor/reflection_ooor.rb

Overview

Holds all the meta-data about an association as it was specified in the Active Record class.

Instance Attribute Summary

Attributes inherited from MacroReflection

#active_record, #connection, #macro, #name, #options, #plural_name

Instance Method Summary collapse

Methods inherited from MacroReflection

#==, #class_name

Constructor Details

#initialize(macro, name, options, active_record) ⇒ AssociationReflection

Returns a new instance of AssociationReflection.



95
96
97
98
# File 'lib/ooor/reflection_ooor.rb', line 95

def initialize(macro, name, options, active_record)
  super
  @collection = macro.in?([:has_many, :has_and_belongs_to_many])
end

Instance Method Details

#build_association(*options, &block) ⇒ Object

Returns a new, unsaved instance of the associated class. options will be passed to the class’s constructor.



102
103
104
# File 'lib/ooor/reflection_ooor.rb', line 102

def build_association(*options, &block)
  klass.new(*options, &block)
end

#collection?Boolean

Returns whether or not this association reflection is for a collection association. Returns true if the macro is either has_many or has_and_belongs_to_many, false otherwise.

Returns:

  • (Boolean)


109
110
111
# File 'lib/ooor/reflection_ooor.rb', line 109

def collection?
  @collection
end

#klassObject

Returns the target association’s class.

class Author < ActiveRecord::Base
  has_many :books
end

Author.reflect_on_association(:books).klass
# => Book

Note: Do not call klass.new or klass.create to instantiate a new association object. Use build_association or create_association instead. This allows plugins to hook into association object creation.



90
91
92
93
# File 'lib/ooor/reflection_ooor.rb', line 90

def klass
#        @klass ||= active_record.send(:compute_type, class_name)
  @klass ||= connection.class_name_from_model_key(class_name).constantize
end