Class: Perry::Association::Has

Inherits:
Base
  • Object
show all
Defined in:
lib/perry/association.rb

Direct Known Subclasses

HasMany, HasOne

Instance Attribute Summary

Attributes inherited from Base

#id, #options, #source_klass

Instance Method Summary collapse

Methods inherited from Base

#collection?, #eager_loadable?, #initialize, #primary_key, #target_klass, #type

Constructor Details

This class inherits a constructor from Perry::Association::Base

Instance Method Details

#foreign_keyObject



190
191
192
193
194
195
196
# File 'lib/perry/association.rb', line 190

def foreign_key
  super || if self.polymorphic?
    "#{options[:as]}_id"
  else
     "#{Perry::Base.base_class_name(source_klass).downcase}_id"
  end.to_sym
end

#polymorphic?Boolean

Returns:

  • (Boolean)


237
238
239
# File 'lib/perry/association.rb', line 237

def polymorphic?
  !!options[:as]
end

#polymorphic_typeObject



233
234
235
# File 'lib/perry/association.rb', line 233

def polymorphic_type
  :"#{options[:as]}_type"
end

#scope(object) ⇒ Object

Returns a scope on the target containing this association

Builds conditions on top of the base_scope generated from any finder options set with the association

has_many :widgets, :class_name => "Widget", :foreign_key => :widget_id
has_many :comments, :as => :parent

In addition to any finder options included with the association options the following will be added:

where(widget_id => source[:id])

Or for the polymorphic :comments association:

where(:parent_id => source[:id], :parent_type => source.class)


217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/perry/association.rb', line 217

def scope(object)
  if object.is_a? Array
    keys = object.collect(&self.primary_key.to_sym)
    keys = nil if keys.empty?
    klass = object.first.class
  else
    keys = object[self.primary_key]
    klass = object.class
  end
  if keys
    scope = base_scope(object).where(self.foreign_key => keys)
    scope = scope.where(polymorphic_type => Perry::Base.base_class_name(klass)) if polymorphic?
    scope
  end
end