Merged updates from trunk into stable branch
[feedcatcher.git] / vendor / rails / activerecord / lib / active_record / reflection.rb
1 module ActiveRecord
2 module Reflection # :nodoc:
3 def self.included(base)
4 base.extend(ClassMethods)
5 end
6
7 # Reflection allows you to interrogate Active Record classes and objects about their associations and aggregations.
8 # This information can, for example, be used in a form builder that took an Active Record object and created input
9 # fields for all of the attributes depending on their type and displayed the associations to other objects.
10 #
11 # You can find the interface for the AggregateReflection and AssociationReflection classes in the abstract MacroReflection class.
12 module ClassMethods
13 def create_reflection(macro, name, options, active_record)
14 case macro
15 when :has_many, :belongs_to, :has_one, :has_and_belongs_to_many
16 klass = options[:through] ? ThroughReflection : AssociationReflection
17 reflection = klass.new(macro, name, options, active_record)
18 when :composed_of
19 reflection = AggregateReflection.new(macro, name, options, active_record)
20 end
21 write_inheritable_hash :reflections, name => reflection
22 reflection
23 end
24
25 # Returns a hash containing all AssociationReflection objects for the current class
26 # Example:
27 #
28 # Invoice.reflections
29 # Account.reflections
30 #
31 def reflections
32 read_inheritable_attribute(:reflections) || write_inheritable_attribute(:reflections, {})
33 end
34
35 # Returns an array of AggregateReflection objects for all the aggregations in the class.
36 def reflect_on_all_aggregations
37 reflections.values.select { |reflection| reflection.is_a?(AggregateReflection) }
38 end
39
40 # Returns the AggregateReflection object for the named +aggregation+ (use the symbol). Example:
41 #
42 # Account.reflect_on_aggregation(:balance) # returns the balance AggregateReflection
43 #
44 def reflect_on_aggregation(aggregation)
45 reflections[aggregation].is_a?(AggregateReflection) ? reflections[aggregation] : nil
46 end
47
48 # Returns an array of AssociationReflection objects for all the associations in the class. If you only want to reflect on a
49 # certain association type, pass in the symbol (<tt>:has_many</tt>, <tt>:has_one</tt>, <tt>:belongs_to</tt>) for that as the first parameter.
50 # Example:
51 #
52 # Account.reflect_on_all_associations # returns an array of all associations
53 # Account.reflect_on_all_associations(:has_many) # returns an array of all has_many associations
54 #
55 def reflect_on_all_associations(macro = nil)
56 association_reflections = reflections.values.select { |reflection| reflection.is_a?(AssociationReflection) }
57 macro ? association_reflections.select { |reflection| reflection.macro == macro } : association_reflections
58 end
59
60 # Returns the AssociationReflection object for the named +association+ (use the symbol). Example:
61 #
62 # Account.reflect_on_association(:owner) # returns the owner AssociationReflection
63 # Invoice.reflect_on_association(:line_items).macro # returns :has_many
64 #
65 def reflect_on_association(association)
66 reflections[association].is_a?(AssociationReflection) ? reflections[association] : nil
67 end
68
69 # Returns an array of AssociationReflection objects for all associations which have <tt>:autosave</tt> enabled.
70 def reflect_on_all_autosave_associations
71 reflections.values.select { |reflection| reflection.options[:autosave] }
72 end
73 end
74
75
76 # Abstract base class for AggregateReflection and AssociationReflection that describes the interface available for both of
77 # those classes. Objects of AggregateReflection and AssociationReflection are returned by the Reflection::ClassMethods.
78 class MacroReflection
79 attr_reader :active_record
80
81 def initialize(macro, name, options, active_record)
82 @macro, @name, @options, @active_record = macro, name, options, active_record
83 end
84
85 # Returns the name of the macro. For example, <tt>composed_of :balance, :class_name => 'Money'</tt> will return
86 # <tt>:balance</tt> or for <tt>has_many :clients</tt> it will return <tt>:clients</tt>.
87 def name
88 @name
89 end
90
91 # Returns the macro type. For example, <tt>composed_of :balance, :class_name => 'Money'</tt> will return <tt>:composed_of</tt>
92 # or for <tt>has_many :clients</tt> will return <tt>:has_many</tt>.
93 def macro
94 @macro
95 end
96
97 # Returns the hash of options used for the macro. For example, it would return <tt>{ :class_name => "Money" }</tt> for
98 # <tt>composed_of :balance, :class_name => 'Money'</tt> or +{}+ for <tt>has_many :clients</tt>.
99 def options
100 @options
101 end
102
103 # Returns the class for the macro. For example, <tt>composed_of :balance, :class_name => 'Money'</tt> returns the Money
104 # class and <tt>has_many :clients</tt> returns the Client class.
105 def klass
106 @klass ||= class_name.constantize
107 end
108
109 # Returns the class name for the macro. For example, <tt>composed_of :balance, :class_name => 'Money'</tt> returns <tt>'Money'</tt>
110 # and <tt>has_many :clients</tt> returns <tt>'Client'</tt>.
111 def class_name
112 @class_name ||= options[:class_name] || derive_class_name
113 end
114
115 # Returns +true+ if +self+ and +other_aggregation+ have the same +name+ attribute, +active_record+ attribute,
116 # and +other_aggregation+ has an options hash assigned to it.
117 def ==(other_aggregation)
118 other_aggregation.kind_of?(self.class) && name == other_aggregation.name && other_aggregation.options && active_record == other_aggregation.active_record
119 end
120
121 def sanitized_conditions #:nodoc:
122 @sanitized_conditions ||= klass.send(:sanitize_sql, options[:conditions]) if options[:conditions]
123 end
124
125 # Returns +true+ if +self+ is a +belongs_to+ reflection.
126 def belongs_to?
127 macro == :belongs_to
128 end
129
130 private
131 def derive_class_name
132 name.to_s.camelize
133 end
134 end
135
136
137 # Holds all the meta-data about an aggregation as it was specified in the Active Record class.
138 class AggregateReflection < MacroReflection #:nodoc:
139 end
140
141 # Holds all the meta-data about an association as it was specified in the Active Record class.
142 class AssociationReflection < MacroReflection #:nodoc:
143 # Returns the target association's class:
144 #
145 # class Author < ActiveRecord::Base
146 # has_many :books
147 # end
148 #
149 # Author.reflect_on_association(:books).klass
150 # # => Book
151 #
152 # <b>Note:</b> do not call +klass.new+ or +klass.create+ to instantiate
153 # a new association object. Use +build_association+ or +create_association+
154 # instead. This allows plugins to hook into association object creation.
155 def klass
156 @klass ||= active_record.send(:compute_type, class_name)
157 end
158
159 # Returns a new, unsaved instance of the associated class. +options+ will
160 # be passed to the class's constructor.
161 def build_association(*options)
162 klass.new(*options)
163 end
164
165 # Creates a new instance of the associated class, and immediates saves it
166 # with ActiveRecord::Base#save. +options+ will be passed to the class's
167 # creation method. Returns the newly created object.
168 def create_association(*options)
169 klass.create(*options)
170 end
171
172 # Creates a new instance of the associated class, and immediates saves it
173 # with ActiveRecord::Base#save!. +options+ will be passed to the class's
174 # creation method. If the created record doesn't pass validations, then an
175 # exception will be raised.
176 #
177 # Returns the newly created object.
178 def create_association!(*options)
179 klass.create!(*options)
180 end
181
182 def table_name
183 @table_name ||= klass.table_name
184 end
185
186 def quoted_table_name
187 @quoted_table_name ||= klass.quoted_table_name
188 end
189
190 def primary_key_name
191 @primary_key_name ||= options[:foreign_key] || derive_primary_key_name
192 end
193
194 def association_foreign_key
195 @association_foreign_key ||= @options[:association_foreign_key] || class_name.foreign_key
196 end
197
198 def counter_cache_column
199 if options[:counter_cache] == true
200 "#{active_record.name.demodulize.underscore.pluralize}_count"
201 elsif options[:counter_cache]
202 options[:counter_cache]
203 end
204 end
205
206 def columns(tbl_name, log_msg)
207 @columns ||= klass.connection.columns(tbl_name, log_msg)
208 end
209
210 def reset_column_information
211 @columns = nil
212 end
213
214 def check_validity!
215 end
216
217 def through_reflection
218 false
219 end
220
221 def through_reflection_primary_key_name
222 end
223
224 def source_reflection
225 nil
226 end
227
228 private
229 def derive_class_name
230 class_name = name.to_s.camelize
231 class_name = class_name.singularize if [ :has_many, :has_and_belongs_to_many ].include?(macro)
232 class_name
233 end
234
235 def derive_primary_key_name
236 if belongs_to?
237 "#{name}_id"
238 elsif options[:as]
239 "#{options[:as]}_id"
240 else
241 active_record.name.foreign_key
242 end
243 end
244 end
245
246 # Holds all the meta-data about a :through association as it was specified in the Active Record class.
247 class ThroughReflection < AssociationReflection #:nodoc:
248 # Gets the source of the through reflection. It checks both a singularized and pluralized form for <tt>:belongs_to</tt> or <tt>:has_many</tt>.
249 # (The <tt>:tags</tt> association on Tagging below.)
250 #
251 # class Post < ActiveRecord::Base
252 # has_many :taggings
253 # has_many :tags, :through => :taggings
254 # end
255 #
256 def source_reflection
257 @source_reflection ||= source_reflection_names.collect { |name| through_reflection.klass.reflect_on_association(name) }.compact.first
258 end
259
260 # Returns the AssociationReflection object specified in the <tt>:through</tt> option
261 # of a HasManyThrough or HasOneThrough association. Example:
262 #
263 # class Post < ActiveRecord::Base
264 # has_many :taggings
265 # has_many :tags, :through => :taggings
266 # end
267 #
268 # tags_reflection = Post.reflect_on_association(:tags)
269 # taggings_reflection = tags_reflection.through_reflection
270 #
271 def through_reflection
272 @through_reflection ||= active_record.reflect_on_association(options[:through])
273 end
274
275 # Gets an array of possible <tt>:through</tt> source reflection names:
276 #
277 # [:singularized, :pluralized]
278 #
279 def source_reflection_names
280 @source_reflection_names ||= (options[:source] ? [options[:source]] : [name.to_s.singularize, name]).collect { |n| n.to_sym }
281 end
282
283 def check_validity!
284 if through_reflection.nil?
285 raise HasManyThroughAssociationNotFoundError.new(active_record.name, self)
286 end
287
288 if source_reflection.nil?
289 raise HasManyThroughSourceAssociationNotFoundError.new(self)
290 end
291
292 if options[:source_type] && source_reflection.options[:polymorphic].nil?
293 raise HasManyThroughAssociationPointlessSourceTypeError.new(active_record.name, self, source_reflection)
294 end
295
296 if source_reflection.options[:polymorphic] && options[:source_type].nil?
297 raise HasManyThroughAssociationPolymorphicError.new(active_record.name, self, source_reflection)
298 end
299
300 unless [:belongs_to, :has_many].include?(source_reflection.macro) && source_reflection.options[:through].nil?
301 raise HasManyThroughSourceAssociationMacroError.new(self)
302 end
303 end
304
305 def through_reflection_primary_key
306 through_reflection.belongs_to? ? through_reflection.klass.primary_key : through_reflection.primary_key_name
307 end
308
309 def through_reflection_primary_key_name
310 through_reflection.primary_key_name if through_reflection.belongs_to?
311 end
312
313 private
314 def derive_class_name
315 # get the class_name of the belongs_to association of the through reflection
316 options[:source_type] || source_reflection.class_name
317 end
318 end
319 end
320 end