Class: RPCMapper::Association::Has

Inherits:
Base
  • Object
show all
Defined in:
lib/rpc_mapper/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 RPCMapper::Association::Base

Instance Method Details

#foreign_keyObject



167
168
169
170
171
172
173
# File 'lib/rpc_mapper/association.rb', line 167

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

#polymorphic?Boolean

Returns:

  • (Boolean)


208
209
210
# File 'lib/rpc_mapper/association.rb', line 208

def polymorphic?
  !!options[:as]
end

#polymorphic_typeObject



204
205
206
# File 'lib/rpc_mapper/association.rb', line 204

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)


194
195
196
197
198
199
200
201
202
# File 'lib/rpc_mapper/association.rb', line 194

def scope(object)
  return nil unless object[self.primary_key]
  s = base_scope(object).where(self.foreign_key => object[self.primary_key])
  if polymorphic?
    s = s.where(
      polymorphic_type => RPCMapper::Base.base_class_name(object.class) )
  end
  s
end