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
)
173 @reflection.klass
.send(:sanitize_sql, sql
)
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 record
[@reflection.primary_key_name
] = @owner.id
unless @owner.new_record
?
187 # Merges into +options+ the ones coming from the reflection.
188 def merge_options_from_reflection
!(options
)
189 options
.reverse_merge
!(
190 :group => @reflection.options
[:group],
191 :limit => @reflection.options
[:limit],
192 :offset => @reflection.options
[:offset],
193 :joins => @reflection.options
[:joins],
194 :include => @reflection.options
[:include],
195 :select => @reflection.options
[:select],
196 :readonly => @reflection.options
[:readonly]
200 # Forwards +with_scope+ to the reflection.
201 def with_scope(*args
, &block
)
202 @reflection.klass
.send
:with_scope, *args
, &block
206 # Forwards any missing method call to the \target.
207 def method_missing(method
, *args
)
209 raise NoMethodError
unless @target.respond_to
?(method
)
212 @target.send(method
, *args
) { |*block_args
| yield(*block_args
) }
214 @target.send(method
, *args
)
219 # Loads the \target if needed and returns it.
221 # This method is abstract in the sense that it relies on +find_target+,
222 # which is expected to be provided by descendants.
224 # If the \target is already \loaded it is just returned. Thus, you can call
225 # +load_target+ unconditionally to get the \target.
227 # ActiveRecord::RecordNotFound is rescued within the method, and it is
228 # not reraised. The proxy is \reset and +nil+ is the return value.
230 return nil unless defined?(@loaded)
232 if !loaded
? and (!@owner.new_record
? || foreign_key_present
)
233 @target = find_target
238 rescue ActiveRecord
::RecordNotFound
242 # Can be overwritten by associations that might have the foreign key
243 # available for an association without having the object itself (and
244 # still being a new record). Currently, only +belongs_to+ presents
245 # this scenario (both vanilla and polymorphic).
246 def foreign_key_present
250 # Raises ActiveRecord::AssociationTypeMismatch unless +record+ is of
251 # the kind of the class of the associated objects. Meant to be used as
252 # a sanity check when you are about to assign an associated record.
253 def raise_on_type_mismatch(record
)
254 unless record
.is_a
?(@reflection.klass
) || record
.is_a
?(@reflection.class_name
.constantize
)
255 message
= "#{@reflection.class_name}(##{@reflection.klass.object_id}) expected, got #{record.class}(##{record.class.object_id})"
256 raise ActiveRecord
::AssociationTypeMismatch, message
260 # Array#flatten has problems with recursive arrays. Going one level
261 # deeper solves the majority of the problems.
262 def flatten_deeper(array
)
263 array
.collect
{ |element
| (element
.respond_to
?(:flatten) && !element
.is_a
?(Hash
)) ? element
.flatten
: element
}.flatten
266 # Returns the ID of the owner, quoted if needed.