Froze rails gems
[depot.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 end
69
70
71 # Abstract base class for AggregateReflection and AssociationReflection that describes the interface available for both of
72 # those classes. Objects of AggregateReflection and AssociationReflection are returned by the Reflection::ClassMethods.
73 class MacroReflection
74 attr_reader :active_record
75
76 def initialize(macro, name, options, active_record)
77 @macro, @name, @options, @active_record = macro, name, options, active_record
78 end
79
80 # Returns the name of the macro. For example, <tt>composed_of :balance, :class_name => 'Money'</tt> will return
81 # <tt>:balance</tt> or for <tt>has_many :clients</tt> it will return <tt>:clients</tt>.
82 def name
83 @name
84 end
85
86 # Returns the macro type. For example, <tt>composed_of :balance, :class_name => 'Money'</tt> will return <tt>:composed_of</tt>
87 # or for <tt>has_many :clients</tt> will return <tt>:has_many</tt>.
88 def macro
89 @macro
90 end
91
92 # Returns the hash of options used for the macro. For example, it would return <tt>{ :class_name => "Money" }</tt> for
93 # <tt>composed_of :balance, :class_name => 'Money'</tt> or +{}+ for <tt>has_many :clients</tt>.
94 def options
95 @options
96 end
97
98 # Returns the class for the macro. For example, <tt>composed_of :balance, :class_name => 'Money'</tt> returns the Money
99 # class and <tt>has_many :clients</tt> returns the Client class.
100 def klass
101 @klass ||= class_name.constantize
102 end
103
104 # Returns the class name for the macro. For example, <tt>composed_of :balance, :class_name => 'Money'</tt> returns <tt>'Money'</tt>
105 # and <tt>has_many :clients</tt> returns <tt>'Client'</tt>.
106 def class_name
107 @class_name ||= options[:class_name] || derive_class_name
108 end
109
110 # Returns +true+ if +self+ and +other_aggregation+ have the same +name+ attribute, +active_record+ attribute,
111 # and +other_aggregation+ has an options hash assigned to it.
112 def ==(other_aggregation)
113 other_aggregation.kind_of?(self.class) && name == other_aggregation.name && other_aggregation.options && active_record == other_aggregation.active_record
114 end
115
116 def sanitized_conditions #:nodoc:
117 @sanitized_conditions ||= klass.send(:sanitize_sql, options[:conditions]) if options[:conditions]
118 end
119
120 # Returns +true+ if +self+ is a +belongs_to+ reflection.
121 def belongs_to?
122 macro == :belongs_to
123 end
124
125 private
126 def derive_class_name
127 name.to_s.camelize
128 end
129 end
130
131
132 # Holds all the meta-data about an aggregation as it was specified in the Active Record class.
133 class AggregateReflection < MacroReflection #:nodoc:
134 end
135
136 # Holds all the meta-data about an association as it was specified in the Active Record class.
137 class AssociationReflection < MacroReflection #:nodoc:
138 # Returns the target association's class:
139 #
140 # class Author < ActiveRecord::Base
141 # has_many :books
142 # end
143 #
144 # Author.reflect_on_association(:books).klass
145 # # => Book
146 #
147 # <b>Note:</b> do not call +klass.new+ or +klass.create+ to instantiate
148 # a new association object. Use +build_association+ or +create_association+
149 # instead. This allows plugins to hook into association object creation.
150 def klass
151 @klass ||= active_record.send(:compute_type, class_name)
152 end
153
154 # Returns a new, unsaved instance of the associated class. +options+ will
155 # be passed to the class's constructor.
156 def build_association(*options)
157 klass.new(*options)
158 end
159
160 # Creates a new instance of the associated class, and immediates saves it
161 # with ActiveRecord::Base#save. +options+ will be passed to the class's
162 # creation method. Returns the newly created object.
163 def create_association(*options)
164 klass.create(*options)
165 end
166
167 # Creates a new instance of the associated class, and immediates saves it
168 # with ActiveRecord::Base#save!. +options+ will be passed to the class's
169 # creation method. If the created record doesn't pass validations, then an
170 # exception will be raised.
171 #
172 # Returns the newly created object.
173 def create_association!(*options)
174 klass.create!(*options)
175 end
176
177 def table_name
178 @table_name ||= klass.table_name
179 end
180
181 def quoted_table_name
182 @quoted_table_name ||= klass.quoted_table_name
183 end
184
185 def primary_key_name
186 @primary_key_name ||= options[:foreign_key] || derive_primary_key_name
187 end
188
189 def association_foreign_key
190 @association_foreign_key ||= @options[:association_foreign_key] || class_name.foreign_key
191 end
192
193 def counter_cache_column
194 if options[:counter_cache] == true
195 "#{active_record.name.underscore.pluralize}_count"
196 elsif options[:counter_cache]
197 options[:counter_cache]
198 end
199 end
200
201 def check_validity!
202 end
203
204 def through_reflection
205 false
206 end
207
208 def through_reflection_primary_key_name
209 end
210
211 def source_reflection
212 nil
213 end
214
215 private
216 def derive_class_name
217 class_name = name.to_s.camelize
218 class_name = class_name.singularize if [ :has_many, :has_and_belongs_to_many ].include?(macro)
219 class_name
220 end
221
222 def derive_primary_key_name
223 if belongs_to?
224 "#{name}_id"
225 elsif options[:as]
226 "#{options[:as]}_id"
227 else
228 active_record.name.foreign_key
229 end
230 end
231 end
232
233 # Holds all the meta-data about a :through association as it was specified in the Active Record class.
234 class ThroughReflection < AssociationReflection #:nodoc:
235 # 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>.
236 # (The <tt>:tags</tt> association on Tagging below.)
237 #
238 # class Post < ActiveRecord::Base
239 # has_many :taggings
240 # has_many :tags, :through => :taggings
241 # end
242 #
243 def source_reflection
244 @source_reflection ||= source_reflection_names.collect { |name| through_reflection.klass.reflect_on_association(name) }.compact.first
245 end
246
247 # Returns the AssociationReflection object specified in the <tt>:through</tt> option
248 # of a HasManyThrough or HasOneThrough association. Example:
249 #
250 # class Post < ActiveRecord::Base
251 # has_many :taggings
252 # has_many :tags, :through => :taggings
253 # end
254 #
255 # tags_reflection = Post.reflect_on_association(:tags)
256 # taggings_reflection = tags_reflection.through_reflection
257 #
258 def through_reflection
259 @through_reflection ||= active_record.reflect_on_association(options[:through])
260 end
261
262 # Gets an array of possible <tt>:through</tt> source reflection names:
263 #
264 # [:singularized, :pluralized]
265 #
266 def source_reflection_names
267 @source_reflection_names ||= (options[:source] ? [options[:source]] : [name.to_s.singularize, name]).collect { |n| n.to_sym }
268 end
269
270 def check_validity!
271 if through_reflection.nil?
272 raise HasManyThroughAssociationNotFoundError.new(active_record.name, self)
273 end
274
275 if source_reflection.nil?
276 raise HasManyThroughSourceAssociationNotFoundError.new(self)
277 end
278
279 if options[:source_type] && source_reflection.options[:polymorphic].nil?
280 raise HasManyThroughAssociationPointlessSourceTypeError.new(active_record.name, self, source_reflection)
281 end
282
283 if source_reflection.options[:polymorphic] && options[:source_type].nil?
284 raise HasManyThroughAssociationPolymorphicError.new(active_record.name, self, source_reflection)
285 end
286
287 unless [:belongs_to, :has_many].include?(source_reflection.macro) && source_reflection.options[:through].nil?
288 raise HasManyThroughSourceAssociationMacroError.new(self)
289 end
290 end
291
292 def through_reflection_primary_key
293 through_reflection.belongs_to? ? through_reflection.klass.primary_key : through_reflection.primary_key_name
294 end
295
296 def through_reflection_primary_key_name
297 through_reflection.primary_key_name if through_reflection.belongs_to?
298 end
299
300 private
301 def derive_class_name
302 # get the class_name of the belongs_to association of the through reflection
303 options[:source_type] || source_reflection.class_name
304 end
305 end
306 end
307 end