3
# This is the root class of all association proxies:
8
# BelongsToPolymorphicAssociation
9
# AssociationCollection
10
# HasAndBelongsToManyAssociation
12
# HasManyThroughAssociation
13
# HasOneThroughAssociation
15
# Association proxies in Active Record are middlemen between the object that
16
# holds the association, known as the <tt>@owner</tt>, and the actual associated
17
# object, known as the <tt>@target</tt>. The kind of association any proxy is
18
# about is available in <tt>@reflection</tt>. That's an instance of the class
19
# ActiveRecord::Reflection::AssociationReflection.
23
# class Blog < ActiveRecord::Base
27
# blog = Blog.find(:first)
29
# the association proxy in <tt>blog.posts</tt> has the object in +blog+ as
30
# <tt>@owner</tt>, the collection of its posts as <tt>@target</tt>, and
31
# the <tt>@reflection</tt> object represents a <tt>:has_many</tt> macro.
33
# This class has most of the basic instance methods removed, and delegates
34
# unknown methods to <tt>@target</tt> via <tt>method_missing</tt>. As a
35
# corner case, it even removes the +class+ method and that's why you get
37
# blog.posts.class # => Array
39
# though the object behind <tt>blog.posts</tt> is not an Array, but an
40
# ActiveRecord::Associations::HasManyAssociation.
42
# The <tt>@target</tt> object is not \loaded until needed. For example,
46
# is computed directly through SQL and does not trigger by itself the
47
# instantiation of the actual post records.
48
class AssociationProxy #:nodoc:
49
alias_method :proxy_respond_to?, :respond_to?
50
alias_method :proxy_extend, :extend
51
delegate :to_param, :to => :proxy_target
52
instance_methods.each { |m| undef_method m unless m =~ /(^__|^nil\?$|^send$|proxy_|^object_id$)/ }
54
def initialize(owner, reflection)
55
@owner, @reflection = owner, reflection
56
Array(reflection.options[:extend]).each { |ext| proxy_extend(ext) }
60
# Returns the owner of the proxy.
65
# Returns the reflection object that represents the association handled
71
# Returns the \target of the proxy, same as +target+.
76
# Does the proxy or its \target respond to +symbol+?
77
def respond_to?(*args)
78
proxy_respond_to?(*args) || (load_target && @target.respond_to?(*args))
81
# Forwards <tt>===</tt> explicitly to the \target because the instance method
82
# removal above doesn't catch it. Loads the \target if needed.
88
# Returns the name of the table of the related class:
90
# post.comments.aliased_table_name # => "comments"
92
def aliased_table_name
93
@reflection.klass.table_name
96
# Returns the SQL string that corresponds to the <tt>:conditions</tt>
97
# option of the macro, if given, or +nil+ otherwise.
99
@conditions ||= interpolate_sql(@reflection.sanitized_conditions) if @reflection.sanitized_conditions
101
alias :sql_conditions :conditions
103
# Resets the \loaded flag to +false+ and sets the \target to +nil+.
109
# Reloads the \target and returns +self+ on success.
113
self unless @target.nil?
116
# Has the \target been already \loaded?
121
# Asserts the \target has been loaded setting the \loaded flag to +true+.
126
# Returns the target of this proxy, same as +proxy_target+.
131
# Sets the target of this proxy to <tt>\target</tt>, and the \loaded flag to +true+.
137
# Forwards the call to the target. Loads the \target if needed.
143
def send(method, *args)
144
if proxy_respond_to?(method)
148
@target.send(method, *args)
153
# Does the association have a <tt>:dependent</tt> option?
155
@reflection.options[:dependent]
158
# Returns a string with the IDs of +records+ joined with a comma, quoted
159
# if needed. The result is ready to be inserted into a SQL IN clause.
161
# quoted_record_ids(records) # => "23,56,58,67"
163
def quoted_record_ids(records)
164
records.map { |record| record.quoted_id }.join(',')
167
def interpolate_sql(sql, record = nil)
168
@owner.send(:interpolate_sql, sql, record)
171
# Forwards the call to the reflection class.
172
def sanitize_sql(sql, table_name = @reflection.klass.quoted_table_name)
173
@reflection.klass.send(:sanitize_sql, sql, table_name)
176
# Assigns the ID of the owner to the corresponding foreign key in +record+.
177
# If the association is polymorphic the type of the owner is also set.
178
def set_belongs_to_association_for(record)
179
if @reflection.options[:as]
180
record["#{@reflection.options[:as]}_id"] = @owner.id unless @owner.new_record?
181
record["#{@reflection.options[:as]}_type"] = @owner.class.base_class.name.to_s
183
unless @owner.new_record?
184
primary_key = @reflection.options[:primary_key] || :id
185
record[@reflection.primary_key_name] = @owner.send(primary_key)
190
# Merges into +options+ the ones coming from the reflection.
191
def merge_options_from_reflection!(options)
192
options.reverse_merge!(
193
:group => @reflection.options[:group],
194
:having => @reflection.options[:having],
195
:limit => @reflection.options[:limit],
196
:offset => @reflection.options[:offset],
197
:joins => @reflection.options[:joins],
198
:include => @reflection.options[:include],
199
:select => @reflection.options[:select],
200
:readonly => @reflection.options[:readonly]
204
# Forwards +with_scope+ to the reflection.
205
def with_scope(*args, &block)
206
@reflection.klass.send :with_scope, *args, &block
210
# Forwards any missing method call to the \target.
211
def method_missing(method, *args)
213
if @target.respond_to?(method)
215
@target.send(method, *args) { |*block_args| yield(*block_args) }
217
@target.send(method, *args)
225
# Loads the \target if needed and returns it.
227
# This method is abstract in the sense that it relies on +find_target+,
228
# which is expected to be provided by descendants.
230
# If the \target is already \loaded it is just returned. Thus, you can call
231
# +load_target+ unconditionally to get the \target.
233
# ActiveRecord::RecordNotFound is rescued within the method, and it is
234
# not reraised. The proxy is \reset and +nil+ is the return value.
236
return nil unless defined?(@loaded)
238
if !loaded? and (!@owner.new_record? || foreign_key_present)
239
@target = find_target
244
rescue ActiveRecord::RecordNotFound
248
# Can be overwritten by associations that might have the foreign key
249
# available for an association without having the object itself (and
250
# still being a new record). Currently, only +belongs_to+ presents
251
# this scenario (both vanilla and polymorphic).
252
def foreign_key_present
256
# Raises ActiveRecord::AssociationTypeMismatch unless +record+ is of
257
# the kind of the class of the associated objects. Meant to be used as
258
# a sanity check when you are about to assign an associated record.
259
def raise_on_type_mismatch(record)
260
unless record.is_a?(@reflection.klass) || record.is_a?(@reflection.class_name.constantize)
261
message = "#{@reflection.class_name}(##{@reflection.klass.object_id}) expected, got #{record.class}(##{record.class.object_id})"
262
raise ActiveRecord::AssociationTypeMismatch, message
266
# Array#flatten has problems with recursive arrays. Going one level
267
# deeper solves the majority of the problems.
268
def flatten_deeper(array)
269
array.collect { |element| (element.respond_to?(:flatten) && !element.is_a?(Hash)) ? element.flatten : element }.flatten
272
# Returns the ID of the owner, quoted if needed.