Module: PGArrays::ReferencesBy::ClassMethods

Included in:
ActiveRecord::Base
Defined in:
lib/ar_pg_array/references_by.rb

Instance Method Summary collapse

Instance Method Details

#references_by_array(relation, options = {}) ⇒ Object



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/ar_pg_array/references_by.rb', line 118

def references_by_array( relation, options = {} )
  unless ActiveSupport::Memoizable === self
    extend ActiveSupport::Memoizable
  end

  relation = relation.to_s.pluralize
  field = "#{relation.singularize}_ids"
  klass_name = (options[:class_name] || relation).to_s.singularize.camelize
  klass = klass_name.constantize
  holder = RelationHolder.new(relation, field, klass )
  
  meths =  Module.new do
    define_method(relation) do
      holder.referenced(self)
    end
    
    define_method("#{relation}=") do |value|
      flush_cache(relation)
      holder.set_referenced(self, value)
    end
  end
  include meths
  
  memoize relation
  
  if options[:validate]
    validate {|o| holder.validate(o)}
  end
  
  holder.for_referenced(self)
end