public
Description: Ruby on Rails
Homepage: http://rubyonrails.org
Clone URL: git://github.com/rails/rails.git
rails / activerecord / lib / active_record / associations.rb
e8550ee0 » jeremy 2009-05-13 Cherry-pick core extensions 1 require 'active_support/core_ext/module/delegation'
ea290e77 » dasil003 2009-11-17 Insert generated associatio... 2 require 'active_support/core_ext/enumerable'
e8550ee0 » jeremy 2009-05-13 Cherry-pick core extensions 3
db045dbb » dhh 2004-11-23 Initial 4 module ActiveRecord
ccea9838 » h-lame 2009-05-01 Providing support for :inve... Comment 5 class InverseOfAssociationNotFoundError < ActiveRecordError #:nodoc:
6 def initialize(reflection)
7 super("Could not find the inverse association for #{reflection.name} (#{reflection.options[:inverse_of].inspect} in #{reflection.class_name})")
8 end
9 end
10
fed7d334 » dhh 2006-03-27 Fixed documentation 11 class HasManyThroughAssociationNotFoundError < ActiveRecordError #:nodoc:
291adbd3 » technoweenie 2006-07-19 fix association exception m... 12 def initialize(owner_class_name, reflection)
13 super("Could not find the association #{reflection.options[:through].inspect} in model #{owner_class_name}")
57af961a » technoweenie 2006-03-18 Raise error when trying to ... 14 end
15 end
16
fed7d334 » dhh 2006-03-27 Fixed documentation 17 class HasManyThroughAssociationPolymorphicError < ActiveRecordError #:nodoc:
57af961a » technoweenie 2006-03-18 Raise error when trying to ... 18 def initialize(owner_class_name, reflection, source_reflection)
291adbd3 » technoweenie 2006-07-19 fix association exception m... 19 super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' on the polymorphic object '#{source_reflection.class_name}##{source_reflection.name}'.")
57af961a » technoweenie 2006-03-18 Raise error when trying to ... 20 end
21 end
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 22
e3dab67c » technoweenie 2007-03-12 Allow a polymorphic :source... 23 class HasManyThroughAssociationPointlessSourceTypeError < ActiveRecordError #:nodoc:
24 def initialize(owner_class_name, reflection, source_reflection)
25 super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' with a :source_type option if the '#{reflection.through_reflection.class_name}##{source_reflection.name}' is not polymorphic. Try removing :source_type on your association.")
26 end
27 end
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 28
fed7d334 » dhh 2006-03-27 Fixed documentation 29 class HasManyThroughSourceAssociationNotFoundError < ActiveRecordError #:nodoc:
38bae0a9 » technoweenie 2006-03-24 Change has_many :through to... 30 def initialize(reflection)
291adbd3 » technoweenie 2006-07-19 fix association exception m... 31 through_reflection = reflection.through_reflection
32 source_reflection_names = reflection.source_reflection_names
33 source_associations = reflection.through_reflection.klass.reflect_on_all_associations.collect { |a| a.name.inspect }
6de83562 » dhh 2009-02-27 Force all internal calls to... 34 super("Could not find the source association(s) #{source_reflection_names.collect(&:inspect).to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)} in model #{through_reflection.klass}. Try 'has_many #{reflection.name.inspect}, :through => #{through_reflection.name.inspect}, :source => <name>'. Is it one of #{source_associations.to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)}?")
57af961a » technoweenie 2006-03-18 Raise error when trying to ... 35 end
36 end
37
0aa0c84c » dhh 2007-01-26 Nodoc the irrelevant (from ... 38 class HasManyThroughSourceAssociationMacroError < ActiveRecordError #:nodoc:
4d232025 » technoweenie 2006-04-05 Added descriptive error mes... 39 def initialize(reflection)
291adbd3 » technoweenie 2006-07-19 fix association exception m... 40 through_reflection = reflection.through_reflection
41 source_reflection = reflection.source_reflection
42 super("Invalid source reflection macro :#{source_reflection.macro}#{" :through" if source_reflection.options[:through]} for has_many #{reflection.name.inspect}, :through => #{through_reflection.name.inspect}. Use :source to specify the source reflection.")
4d232025 » technoweenie 2006-04-05 Added descriptive error mes... 43 end
44 end
45
00d6c766 » dasil003 2009-08-09 Enable has_many :through fo... 46 class HasManyThroughCantAssociateThroughHasOneOrManyReflection < ActiveRecordError #:nodoc:
f6b12c11 » lifo 2008-04-05 Refactor HasManyThroughAsso... 47 def initialize(owner, reflection)
48 super("Cannot modify association '#{owner.class.name}##{reflection.name}' because the source reflection class '#{reflection.source_reflection.class_name}' is associated to '#{reflection.through_reflection.class_name}' via :#{reflection.source_reflection.macro}.")
49 end
50 end
00d6c766 » dasil003 2009-08-09 Enable has_many :through fo... 51
0da426be » jeremy 2006-08-18 Add records to has_many :th... 52 class HasManyThroughCantAssociateNewRecords < ActiveRecordError #:nodoc:
53 def initialize(owner, reflection)
54 super("Cannot associate new records through '#{owner.class.name}##{reflection.name}' on '#{reflection.source_reflection.class_name rescue nil}##{reflection.source_reflection.name rescue nil}'. Both records must have an id in order to create the has_many :through record associating them.")
55 end
56 end
57
4b639904 » jeremy 2007-10-27 Fix has_many :through delet... 58 class HasManyThroughCantDissociateNewRecords < ActiveRecordError #:nodoc:
59 def initialize(owner, reflection)
60 super("Cannot dissociate new records through '#{owner.class.name}##{reflection.name}' on '#{reflection.source_reflection.class_name rescue nil}##{reflection.source_reflection.name rescue nil}'. Both records must have an id in order to delete the has_many :through record associating them.")
61 end
62 end
63
78790e47 » jeremy 2009-11-23 Revert "Revert "Assert prim... 64 class HasAndBelongsToManyAssociationWithPrimaryKeyError < ActiveRecordError #:nodoc:
65 def initialize(reflection)
66 super("Primary key is not allowed in a has_and_belongs_to_many join table (#{reflection.options[:join_table]}).")
67 end
68 end
69
c896d56c » cwninja 2009-03-06 Ensure self referential HAB... 70 class HasAndBelongsToManyAssociationForeignKeyNeeded < ActiveRecordError #:nodoc:
71 def initialize(reflection)
72 super("Cannot create self referential has_and_belongs_to_many association on '#{reflection.class_name rescue nil}##{reflection.name rescue nil}'. :association_foreign_key cannot be the same as the :foreign_key.")
73 end
74 end
75
fed7d334 » dhh 2006-03-27 Fixed documentation 76 class EagerLoadPolymorphicError < ActiveRecordError #:nodoc:
57af961a » technoweenie 2006-03-18 Raise error when trying to ... 77 def initialize(reflection)
291adbd3 » technoweenie 2006-07-19 fix association exception m... 78 super("Can not eagerly load the polymorphic association #{reflection.name.inspect}")
57af961a » technoweenie 2006-03-18 Raise error when trying to ... 79 end
80 end
81
c61b10b6 » technoweenie 2006-04-24 Raise error when trying to ... 82 class ReadOnlyAssociation < ActiveRecordError #:nodoc:
83 def initialize(reflection)
291adbd3 » technoweenie 2006-07-19 fix association exception m... 84 super("Can not add to a has_many :through association. Try adding to #{reflection.through_reflection.name.inspect}.")
c61b10b6 » technoweenie 2006-04-24 Raise error when trying to ... 85 end
86 end
87
6e754551 » lifo 2008-07-28 Merge docrails changes 88 # See ActiveRecord::Associations::ClassMethods for documentation.
db045dbb » dhh 2004-11-23 Initial 89 module Associations # :nodoc:
4e50a35f » josh 2009-05-28 Break up DependencyModule's... 90 extend ActiveSupport::Concern
a2875bec » brynary 2009-05-11 Use DependencyModule for in... 91
f3651365 » amilligan 2009-03-07 Fix RDoc grammar and ensure... 92 # These classes will be loaded when associations are created.
7254d237 » josh 2008-11-24 Autoload ActiveRecord files 93 # So there is no need to eager load them.
94 autoload :AssociationCollection, 'active_record/associations/association_collection'
95 autoload :AssociationProxy, 'active_record/associations/association_proxy'
96 autoload :BelongsToAssociation, 'active_record/associations/belongs_to_association'
97 autoload :BelongsToPolymorphicAssociation, 'active_record/associations/belongs_to_polymorphic_association'
98 autoload :HasAndBelongsToManyAssociation, 'active_record/associations/has_and_belongs_to_many_association'
99 autoload :HasManyAssociation, 'active_record/associations/has_many_association'
100 autoload :HasManyThroughAssociation, 'active_record/associations/has_many_through_association'
101 autoload :HasOneAssociation, 'active_record/associations/has_one_association'
102 autoload :HasOneThroughAssociation, 'active_record/associations/has_one_through_association'
103
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 104 # Clears out the association cache
4b229d10 » dhh 2004-12-22 Added Base#clear_associatio... 105 def clear_association_cache #:nodoc:
106 self.class.reflect_on_all_associations.to_a.each do |assoc|
107 instance_variable_set "@#{assoc.name}", nil
85fbb22f » dhh 2006-09-05 Backed out of new_record? t... 108 end unless self.new_record?
4b229d10 » dhh 2004-12-22 Added Base#clear_associatio... 109 end
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 110
ec8f0458 » alloy 2009-01-31 Add support for nested obje... Comment 111 private
112 # Gets the specified association instance if it responds to :loaded?, nil otherwise.
113 def association_instance_get(name)
114 association = instance_variable_get("@#{name}")
115 association if association.respond_to?(:loaded?)
116 end
117
118 # Set the specified association instance.
119 def association_instance_set(name, association)
120 instance_variable_set("@#{name}", association)
121 end
122
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 123 # Associations are a set of macro-like class methods for tying objects together through foreign keys. They express relationships like
124 # "Project has one Project Manager" or "Project belongs to a Portfolio". Each macro adds a number of methods to the class which are
125 # specialized according to the collection or association symbol and the options hash. It works much the same way as Ruby's own <tt>attr*</tt>
db045dbb » dhh 2004-11-23 Initial 126 # methods. Example:
127 #
128 # class Project < ActiveRecord::Base
129 # belongs_to :portfolio
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 130 # has_one :project_manager
db045dbb » dhh 2004-11-23 Initial 131 # has_many :milestones
132 # has_and_belongs_to_many :categories
133 # end
134 #
135 # The project class now has the following methods (and more) to ease the traversal and manipulation of its relationships:
823554ea » dhh 2005-01-15 Added support for associati... 136 # * <tt>Project#portfolio, Project#portfolio=(portfolio), Project#portfolio.nil?</tt>
db045dbb » dhh 2004-11-23 Initial 137 # * <tt>Project#project_manager, Project#project_manager=(project_manager), Project#project_manager.nil?,</tt>
138 # * <tt>Project#milestones.empty?, Project#milestones.size, Project#milestones, Project#milestones<<(milestone),</tt>
7aa9eed8 » jeremy 2006-09-01 Deprecation: update docs. C... 139 # <tt>Project#milestones.delete(milestone), Project#milestones.find(milestone_id), Project#milestones.find(:all, options),</tt>
db045dbb » dhh 2004-11-23 Initial 140 # <tt>Project#milestones.build, Project#milestones.create</tt>
141 # * <tt>Project#categories.empty?, Project#categories.size, Project#categories, Project#categories<<(category1),</tt>
142 # <tt>Project#categories.delete(category1)</tt>
143 #
7288fd3e » jeremy 2007-05-18 Docs: warn that association... 144 # === A word of warning
145 #
146 # Don't create associations that have the same name as instance methods of ActiveRecord::Base. Since the association
147 # adds a method with that name to its model, it will override the inherited method and break things.
dc4eec11 » lifo 2008-05-09 Merge docrails: 148 # For instance, +attributes+ and +connection+ would be bad choices for association names.
7288fd3e » jeremy 2007-05-18 Docs: warn that association... 149 #
ff6d2aae » jeremy 2007-05-30 Quickref for association me... 150 # == Auto-generated methods
db045dbb » dhh 2004-11-23 Initial 151 #
c23c9bd1 » technoweenie 2008-03-21 Allow association scoping f... 152 # === Singular associations (one-to-one)
ff6d2aae » jeremy 2007-05-30 Quickref for association me... 153 # | | belongs_to |
154 # generated methods | belongs_to | :polymorphic | has_one
155 # ----------------------------------+------------+--------------+---------
53cd102b » lifo 2009-02-24 Merge with docrails 156 # other | X | X | X
157 # other=(other) | X | X | X
158 # build_other(attributes={}) | X | | X
159 # create_other(attributes={}) | X | | X
160 # other.create!(attributes={}) | | | X
ff6d2aae » jeremy 2007-05-30 Quickref for association me... 161 #
162 # ===Collection associations (one-to-many / many-to-many)
163 # | | | has_many
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 164 # generated methods | habtm | has_many | :through
ff6d2aae » jeremy 2007-05-30 Quickref for association me... 165 # ----------------------------------+-------+----------+----------
53cd102b » lifo 2009-02-24 Merge with docrails 166 # others | X | X | X
167 # others=(other,other,...) | X | X | X
168 # other_ids | X | X | X
169 # other_ids=(id,id,...) | X | X | X
170 # others<< | X | X | X
171 # others.push | X | X | X
172 # others.concat | X | X | X
173 # others.build(attributes={}) | X | X | X
174 # others.create(attributes={}) | X | X | X
175 # others.create!(attributes={}) | X | X | X
176 # others.size | X | X | X
177 # others.length | X | X | X
178 # others.count | X | X | X
179 # others.sum(args*,&block) | X | X | X
180 # others.empty? | X | X | X
181 # others.clear | X | X | X
182 # others.delete(other,other,...) | X | X | X
183 # others.delete_all | X | X |
184 # others.destroy_all | X | X | X
185 # others.find(*args) | X | X | X
186 # others.find_first | X | |
187 # others.exists? | X | X | X
188 # others.uniq | X | X | X
189 # others.reset | X | X | X
db045dbb » dhh 2004-11-23 Initial 190 #
51d840e2 » NZKoz 2007-01-14 Improve association documen... 191 # == Cardinality and associations
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 192 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 193 # Active Record associations can be used to describe one-to-one, one-to-many and many-to-many
aa4af60a » lifo 2008-04-04 Improve documentation. 194 # relationships between models. Each model uses an association to describe its role in
195 # the relation. The +belongs_to+ association is always used in the model that has
8296c680 » technoweenie 2007-01-22 Remove useless code in #att... 196 # the foreign key.
51d840e2 » NZKoz 2007-01-14 Improve association documen... 197 #
198 # === One-to-one
199 #
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 200 # Use +has_one+ in the base, and +belongs_to+ in the associated model.
51d840e2 » NZKoz 2007-01-14 Improve association documen... 201 #
202 # class Employee < ActiveRecord::Base
203 # has_one :office
204 # end
205 # class Office < ActiveRecord::Base
206 # belongs_to :employee # foreign key - employee_id
207 # end
208 #
209 # === One-to-many
210 #
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 211 # Use +has_many+ in the base, and +belongs_to+ in the associated model.
51d840e2 » NZKoz 2007-01-14 Improve association documen... 212 #
213 # class Manager < ActiveRecord::Base
214 # has_many :employees
215 # end
216 # class Employee < ActiveRecord::Base
8296c680 » technoweenie 2007-01-22 Remove useless code in #att... 217 # belongs_to :manager # foreign key - manager_id
51d840e2 » NZKoz 2007-01-14 Improve association documen... 218 # end
219 #
220 # === Many-to-many
221 #
222 # There are two ways to build a many-to-many relationship.
223 #
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 224 # The first way uses a +has_many+ association with the <tt>:through</tt> option and a join model, so
51d840e2 » NZKoz 2007-01-14 Improve association documen... 225 # there are two stages of associations.
226 #
227 # class Assignment < ActiveRecord::Base
228 # belongs_to :programmer # foreign key - programmer_id
229 # belongs_to :project # foreign key - project_id
230 # end
231 # class Programmer < ActiveRecord::Base
232 # has_many :assignments
233 # has_many :projects, :through => :assignments
234 # end
235 # class Project < ActiveRecord::Base
236 # has_many :assignments
237 # has_many :programmers, :through => :assignments
238 # end
239 #
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 240 # For the second way, use +has_and_belongs_to_many+ in both models. This requires a join table
51d840e2 » NZKoz 2007-01-14 Improve association documen... 241 # that has no corresponding model or primary key.
242 #
243 # class Programmer < ActiveRecord::Base
244 # has_and_belongs_to_many :projects # foreign keys in the join table
245 # end
246 # class Project < ActiveRecord::Base
247 # has_and_belongs_to_many :programmers # foreign keys in the join table
248 # end
249 #
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 250 # Choosing which way to build a many-to-many relationship is not always simple.
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 251 # If you need to work with the relationship model as its own entity,
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 252 # use <tt>has_many :through</tt>. Use +has_and_belongs_to_many+ when working with legacy schemas or when
51d840e2 » NZKoz 2007-01-14 Improve association documen... 253 # you never work directly with the relationship itself.
254 #
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 255 # == Is it a +belongs_to+ or +has_one+ association?
db045dbb » dhh 2004-11-23 Initial 256 #
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 257 # Both express a 1-1 relationship. The difference is mostly where to place the foreign key, which goes on the table for the class
258 # declaring the +belongs_to+ relationship. Example:
db045dbb » dhh 2004-11-23 Initial 259 #
69d8ca4c » jeremy 2006-07-07 Clearer has_one/belongs_to ... 260 # class User < ActiveRecord::Base
261 # # I reference an account.
262 # belongs_to :account
db045dbb » dhh 2004-11-23 Initial 263 # end
264 #
69d8ca4c » jeremy 2006-07-07 Clearer has_one/belongs_to ... 265 # class Account < ActiveRecord::Base
266 # # One user references me.
267 # has_one :user
db045dbb » dhh 2004-11-23 Initial 268 # end
269 #
270 # The tables for these classes could look something like:
271 #
69d8ca4c » jeremy 2006-07-07 Clearer has_one/belongs_to ... 272 # CREATE TABLE users (
db045dbb » dhh 2004-11-23 Initial 273 # id int(11) NOT NULL auto_increment,
69d8ca4c » jeremy 2006-07-07 Clearer has_one/belongs_to ... 274 # account_id int(11) default NULL,
275 # name varchar default NULL,
db045dbb » dhh 2004-11-23 Initial 276 # PRIMARY KEY (id)
277 # )
278 #
69d8ca4c » jeremy 2006-07-07 Clearer has_one/belongs_to ... 279 # CREATE TABLE accounts (
db045dbb » dhh 2004-11-23 Initial 280 # id int(11) NOT NULL auto_increment,
281 # name varchar default NULL,
282 # PRIMARY KEY (id)
283 # )
284 #
823554ea » dhh 2005-01-15 Added support for associati... 285 # == Unsaved objects and associations
286 #
7143d801 » Marcel Molina 2007-11-07 Smattering of grammatical f... 287 # You can manipulate objects and associations before they are saved to the database, but there is some special behavior you should be
823554ea » dhh 2005-01-15 Added support for associati... 288 # aware of, mostly involving the saving of associated objects.
289 #
580ec0dc » alloy 2009-07-11 Added some documentation ab... 290 # Unless you set the :autosave option on a <tt>has_one</tt>, <tt>belongs_to</tt>,
291 # <tt>has_many</tt>, or <tt>has_and_belongs_to_many</tt> association. Setting it
292 # to +true+ will _always_ save the members, whereas setting it to +false+ will
293 # _never_ save the members.
ec8f0458 » alloy 2009-01-31 Add support for nested obje... Comment 294 #
823554ea » dhh 2005-01-15 Added support for associati... 295 # === One-to-one associations
296 #
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 297 # * Assigning an object to a +has_one+ association automatically saves that object and the object being replaced (if there is one), in
298 # order to update their primary keys - except if the parent object is unsaved (<tt>new_record? == true</tt>).
299 # * If either of these saves fail (due to one of the objects being invalid) the assignment statement returns +false+ and the assignment
823554ea » dhh 2005-01-15 Added support for associati... 300 # is cancelled.
dc4eec11 » lifo 2008-05-09 Merge docrails: 301 # * If you wish to assign an object to a +has_one+ association without saving it, use the <tt>association.build</tt> method (documented below).
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 302 # * Assigning an object to a +belongs_to+ association does not save the object, since the foreign key field belongs on the parent. It
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 303 # does not save the parent either.
823554ea » dhh 2005-01-15 Added support for associati... 304 #
305 # === Collections
306 #
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 307 # * Adding an object to a collection (+has_many+ or +has_and_belongs_to_many+) automatically saves that object, except if the parent object
823554ea » dhh 2005-01-15 Added support for associati... 308 # (the owner of the collection) is not yet stored in the database.
dc4eec11 » lifo 2008-05-09 Merge docrails: 309 # * If saving any of the objects being added to a collection (via <tt>push</tt> or similar) fails, then <tt>push</tt> returns +false+.
310 # * You can add an object to a collection without automatically saving it by using the <tt>collection.build</tt> method (documented below).
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 311 # * All unsaved (<tt>new_record? == true</tt>) members of the collection are automatically saved when the parent is saved.
823554ea » dhh 2005-01-15 Added support for associati... 312 #
17f7f8a0 » dhh 2005-07-06 Made documentation ready fo... 313 # === Association callbacks
4180e57b » dhh 2005-07-04 Added callback hooks to ass... 314 #
2af36bbb » dhh 2007-12-05 Fix typos (closes #10378) 315 # Similar to the normal callbacks that hook into the lifecycle of an Active Record object, you can also define callbacks that get
7143d801 » Marcel Molina 2007-11-07 Smattering of grammatical f... 316 # triggered when you add an object to or remove an object from an association collection. Example:
4180e57b » dhh 2005-07-04 Added callback hooks to ass... 317 #
318 # class Project
319 # has_and_belongs_to_many :developers, :after_add => :evaluate_velocity
320 #
321 # def evaluate_velocity(developer)
322 # ...
323 # end
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 324 # end
4180e57b » dhh 2005-07-04 Added callback hooks to ass... 325 #
326 # It's possible to stack callbacks by passing them as an array. Example:
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 327 #
4180e57b » dhh 2005-07-04 Added callback hooks to ass... 328 # class Project
17f7f8a0 » dhh 2005-07-06 Made documentation ready fo... 329 # has_and_belongs_to_many :developers, :after_add => [:evaluate_velocity, Proc.new { |p, d| p.shipping_date = Time.now}]
4180e57b » dhh 2005-07-04 Added callback hooks to ass... 330 # end
331 #
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 332 # Possible callbacks are: +before_add+, +after_add+, +before_remove+ and +after_remove+.
4180e57b » dhh 2005-07-04 Added callback hooks to ass... 333 #
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 334 # Should any of the +before_add+ callbacks throw an exception, the object does not get added to the collection. Same with
335 # the +before_remove+ callbacks; if an exception is thrown the object doesn't get removed.
4180e57b » dhh 2005-07-04 Added callback hooks to ass... 336 #
8c512a1c » dhh 2005-11-03 Added extension capabilitie... 337 # === Association extensions
338 #
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 339 # The proxy objects that control the access to associations can be extended through anonymous modules. This is especially
3c01e01d » Marcel Molina 2005-12-19 Fix typo in association doc... 340 # beneficial for adding new finders, creators, and other factory-type methods that are only used as part of this association.
8c512a1c » dhh 2005-11-03 Added extension capabilitie... 341 # Example:
342 #
343 # class Account < ActiveRecord::Base
c8dd66fd » dhh 2005-11-06 Made association extensions... 344 # has_many :people do
8c512a1c » dhh 2005-11-03 Added extension capabilitie... 345 # def find_or_create_by_name(name)
e5d9ad3e » dhh 2005-12-12 Added option inheritance fo... 346 # first_name, last_name = name.split(" ", 2)
da7752e5 » dhh 2005-11-06 Sharper example 347 # find_or_create_by_first_name_and_last_name(first_name, last_name)
8c512a1c » dhh 2005-11-03 Added extension capabilitie... 348 # end
c8dd66fd » dhh 2005-11-06 Made association extensions... 349 # end
8c512a1c » dhh 2005-11-03 Added extension capabilitie... 350 # end
351 #
352 # person = Account.find(:first).people.find_or_create_by_name("David Heinemeier Hansson")
353 # person.first_name # => "David"
354 # person.last_name # => "Heinemeier Hansson"
355 #
c8dd66fd » dhh 2005-11-06 Made association extensions... 356 # If you need to share the same extensions between many associations, you can use a named extension module. Example:
357 #
358 # module FindOrCreateByNameExtension
359 # def find_or_create_by_name(name)
e5d9ad3e » dhh 2005-12-12 Added option inheritance fo... 360 # first_name, last_name = name.split(" ", 2)
da7752e5 » dhh 2005-11-06 Sharper example 361 # find_or_create_by_first_name_and_last_name(first_name, last_name)
c8dd66fd » dhh 2005-11-06 Made association extensions... 362 # end
363 # end
364 #
365 # class Account < ActiveRecord::Base
366 # has_many :people, :extend => FindOrCreateByNameExtension
367 # end
368 #
369 # class Company < ActiveRecord::Base
370 # has_many :people, :extend => FindOrCreateByNameExtension
371 # end
8c512a1c » dhh 2005-11-03 Added extension capabilitie... 372 #
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 373 # If you need to use multiple named extension modules, you can specify an array of modules with the <tt>:extend</tt> option.
7e76740d » technoweenie 2006-04-10 Allow multiple association... 374 # In the case of name conflicts between methods in the modules, methods in modules later in the array supercede
375 # those earlier in the array. Example:
376 #
377 # class Account < ActiveRecord::Base
378 # has_many :people, :extend => [FindOrCreateByNameExtension, FindRecentExtension]
379 # end
380 #
ea51d72e » technoweenie 2006-05-28 Provide Association Extensi... 381 # Some extensions can only be made to work with knowledge of the association proxy's internals.
382 # Extensions can access relevant state using accessors on the association proxy:
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 383 #
ea51d72e » technoweenie 2006-05-28 Provide Association Extensi... 384 # * +proxy_owner+ - Returns the object the association is part of.
385 # * +proxy_reflection+ - Returns the reflection object that describes the association.
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 386 # * +proxy_target+ - Returns the associated object for +belongs_to+ and +has_one+, or the collection of associated objects for +has_many+ and +has_and_belongs_to_many+.
ea51d72e » technoweenie 2006-05-28 Provide Association Extensi... 387 #
2597bd69 » technoweenie 2006-03-27 documentation for polymorph... 388 # === Association Join Models
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 389 #
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 390 # Has Many associations can be configured with the <tt>:through</tt> option to use an explicit join model to retrieve the data. This
391 # operates similarly to a +has_and_belongs_to_many+ association. The advantage is that you're able to add validations,
38bae0a9 » technoweenie 2006-03-24 Change has_many :through to... 392 # callbacks, and extra attributes on the join model. Consider the following schema:
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 393 #
38bae0a9 » technoweenie 2006-03-24 Change has_many :through to... 394 # class Author < ActiveRecord::Base
395 # has_many :authorships
396 # has_many :books, :through => :authorships
397 # end
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 398 #
38bae0a9 » technoweenie 2006-03-24 Change has_many :through to... 399 # class Authorship < ActiveRecord::Base
400 # belongs_to :author
401 # belongs_to :book
402 # end
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 403 #
38bae0a9 » technoweenie 2006-03-24 Change has_many :through to... 404 # @author = Author.find :first
405 # @author.authorships.collect { |a| a.book } # selects all books that the author's authorships belong to.
406 # @author.books # selects all books by using the Authorship join model
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 407 #
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 408 # You can also go through a +has_many+ association on the join model:
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 409 #
38bae0a9 » technoweenie 2006-03-24 Change has_many :through to... 410 # class Firm < ActiveRecord::Base
411 # has_many :clients
412 # has_many :invoices, :through => :clients
413 # end
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 414 #
38bae0a9 » technoweenie 2006-03-24 Change has_many :through to... 415 # class Client < ActiveRecord::Base
416 # belongs_to :firm
417 # has_many :invoices
418 # end
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 419 #
38bae0a9 » technoweenie 2006-03-24 Change has_many :through to... 420 # class Invoice < ActiveRecord::Base
421 # belongs_to :client
422 # end
423 #
424 # @firm = Firm.find :first
425 # @firm.clients.collect { |c| c.invoices }.flatten # select all invoices for all clients of the firm
426 # @firm.invoices # selects all invoices by going through the Client join model.
427 #
00d6c766 » dasil003 2009-08-09 Enable has_many :through fo... 428 # Similarly you can go through a +has_one+ association on the join model:
429 #
430 # class Group < ActiveRecord::Base
431 # has_many :users
432 # has_many :avatars, :through => :users
433 # end
434 #
435 # class User < ActiveRecord::Base
436 # belongs_to :group
437 # has_one :avatar
438 # end
439 #
440 # class Avatar < ActiveRecord::Base
441 # belongs_to :user
442 # end
443 #
444 # @group = Group.first
445 # @group.users.collect { |u| u.avatar }.flatten # select all avatars for all users in the group
446 # @group.avatars # selects all avatars by going through the User join model.
447 #
0e2fbd80 » miloops 2009-08-10 Merge commit 'rails/master' 448 # An important caveat with going through +has_one+ or +has_many+ associations on the join model is that these associations are
00d6c766 » dasil003 2009-08-09 Enable has_many :through fo... 449 # *read-only*. For example, the following would not work following the previous example:
450 #
451 # @group.avatars << Avatar.new # this would work if User belonged_to Avatar rather than the other way around.
452 # @group.avatars.delete(@group.avatars.last) # so would this
453 #
2597bd69 » technoweenie 2006-03-27 documentation for polymorph... 454 # === Polymorphic Associations
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 455 #
456 # Polymorphic associations on models are not restricted on what types of models they can be associated with. Rather, they
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 457 # specify an interface that a +has_many+ association must adhere to.
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 458 #
2597bd69 » technoweenie 2006-03-27 documentation for polymorph... 459 # class Asset < ActiveRecord::Base
460 # belongs_to :attachable, :polymorphic => true
461 # end
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 462 #
2597bd69 » technoweenie 2006-03-27 documentation for polymorph... 463 # class Post < ActiveRecord::Base
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 464 # has_many :assets, :as => :attachable # The :as option specifies the polymorphic interface to use.
2597bd69 » technoweenie 2006-03-27 documentation for polymorph... 465 # end
466 #
467 # @asset.attachable = @post
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 468 #
2597bd69 » technoweenie 2006-03-27 documentation for polymorph... 469 # This works by using a type column in addition to a foreign key to specify the associated record. In the Asset example, you'd need
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 470 # an +attachable_id+ integer column and an +attachable_type+ string column.
2597bd69 » technoweenie 2006-03-27 documentation for polymorph... 471 #
fc7fd4c5 » dhh 2006-10-08 Docfix (closes #6040) 472 # Using polymorphic associations in combination with single table inheritance (STI) is a little tricky. In order
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 473 # for the associations to work as expected, ensure that you store the base model for the STI models in the
fc7fd4c5 » dhh 2006-10-08 Docfix (closes #6040) 474 # type column of the polymorphic association. To continue with the asset example above, suppose there are guest posts
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 475 # and member posts that use the posts table for STI. In this case, there must be a +type+ column in the posts table.
fc7fd4c5 » dhh 2006-10-08 Docfix (closes #6040) 476 #
477 # class Asset < ActiveRecord::Base
478 # belongs_to :attachable, :polymorphic => true
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 479 #
fc7fd4c5 » dhh 2006-10-08 Docfix (closes #6040) 480 # def attachable_type=(sType)
481 # super(sType.to_s.classify.constantize.base_class.to_s)
482 # end
483 # end
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 484 #
fc7fd4c5 » dhh 2006-10-08 Docfix (closes #6040) 485 # class Post < ActiveRecord::Base
486 # # because we store "Post" in attachable_type now :dependent => :destroy will work
487 # has_many :assets, :as => :attachable, :dependent => :destroy
488 # end
489 #
aa9ed408 » Marcel Molina 2007-12-05 Fix typo in documentation f... 490 # class GuestPost < Post
fc7fd4c5 » dhh 2006-10-08 Docfix (closes #6040) 491 # end
492 #
aa9ed408 » Marcel Molina 2007-12-05 Fix typo in documentation f... 493 # class MemberPost < Post
fc7fd4c5 » dhh 2006-10-08 Docfix (closes #6040) 494 # end
495 #
db045dbb » dhh 2004-11-23 Initial 496 # == Caching
497 #
498 # All of the methods are built on a simple caching principle that will keep the result of the last query around unless specifically
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 499 # instructed not to. The cache is even shared across methods to make it even cheaper to use the macro-added methods without
db045dbb » dhh 2004-11-23 Initial 500 # worrying too much about performance at the first go. Example:
501 #
502 # project.milestones # fetches milestones from the database
503 # project.milestones.size # uses the milestone cache
504 # project.milestones.empty? # uses the milestone cache
505 # project.milestones(true).size # fetches milestones from the database
506 # project.milestones # uses the milestone cache
507 #
515886a5 » dhh 2005-04-18 Added documentation for new... 508 # == Eager loading of associations
509 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 510 # Eager loading is a way to find objects of a certain class and a number of named associations. This is
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 511 # one of the easiest ways of to prevent the dreaded 1+N problem in which fetching 100 posts that each need to display their author
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 512 # triggers 101 database queries. Through the use of eager loading, the 101 queries can be reduced to 2. Example:
515886a5 » dhh 2005-04-18 Added documentation for new... 513 #
514 # class Post < ActiveRecord::Base
515 # belongs_to :author
516 # has_many :comments
517 # end
518 #
519 # Consider the following loop using the class above:
520 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 521 # for post in Post.all
515886a5 » dhh 2005-04-18 Added documentation for new... 522 # puts "Post: " + post.title
523 # puts "Written by: " + post.author.name
524 # puts "Last comment on: " + post.comments.first.created_on
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 525 # end
515886a5 » dhh 2005-04-18 Added documentation for new... 526 #
527 # To iterate over these one hundred posts, we'll generate 201 database queries. Let's first just optimize it for retrieving the author:
528 #
4e2f7bec » dhh 2005-04-19 Added documentation about :... 529 # for post in Post.find(:all, :include => :author)
515886a5 » dhh 2005-04-18 Added documentation for new... 530 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 531 # This references the name of the +belongs_to+ association that also used the <tt>:author</tt> symbol. After loading the posts, find
532 # will collect the +author_id+ from each one and load all the referenced authors with one query. Doing so will cut down the number of queries from 201 to 102.
515886a5 » dhh 2005-04-18 Added documentation for new... 533 #
534 # We can improve upon the situation further by referencing both associations in the finder with:
535 #
4e2f7bec » dhh 2005-04-19 Added documentation about :... 536 # for post in Post.find(:all, :include => [ :author, :comments ])
515886a5 » dhh 2005-04-18 Added documentation for new... 537 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 538 # This will load all comments with a single query. This reduces the total number of queries to 3. More generally the number of queries
539 # will be 1 plus the number of associations named (except if some of the associations are polymorphic +belongs_to+ - see below).
5b414190 » jeremy 2007-05-19 Document deep eager include... 540 #
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 541 # To include a deep hierarchy of associations, use a hash:
5b414190 » jeremy 2007-05-19 Document deep eager include... 542 #
543 # for post in Post.find(:all, :include => [ :author, { :comments => { :author => :gravatar } } ])
544 #
545 # That'll grab not only all the comments but all their authors and gravatar pictures. You can mix and match
546 # symbols, arrays and hashes in any combination to describe the associations you want to load.
547 #
548 # All of this power shouldn't fool you into thinking that you can pull out huge amounts of data with no performance penalty just because you've reduced
a8eea0b0 » dhh 2005-10-26 Fix docs (closes #2491) 549 # the number of queries. The database still needs to send all the data to Active Record and it still needs to be processed. So it's no
550 # catch-all for performance problems, but it's a great way to cut down on the number of queries in a situation as the one described above.
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 551 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 552 # Since only one table is loaded at a time, conditions or orders cannot reference tables other than the main one. If this is the case
553 # Active Record falls back to the previously used LEFT OUTER JOIN based strategy. For example
19d2ff83 » miloops 2009-04-29 Calculations now use Arel t... 554 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 555 # Post.find(:all, :include => [ :author, :comments ], :conditions => ['comments.approved = ?', true])
515886a5 » dhh 2005-04-18 Added documentation for new... 556 #
e033b5d0 » lifo 2009-07-25 Merge docrails 557 # This will result in a single SQL query with joins along the lines of: <tt>LEFT OUTER JOIN comments ON comments.post_id = posts.id</tt> and
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 558 # <tt>LEFT OUTER JOIN authors ON authors.id = posts.author_id</tt>. Note that using conditions like this can have unintended consequences.
559 # In the above example posts with no approved comments are not returned at all, because the conditions apply to the SQL statement as a whole
560 # and not just to the association. You must disambiguate column references for this fallback to happen, for example
19d2ff83 » miloops 2009-04-29 Calculations now use Arel t... 561 # <tt>:order => "author.name DESC"</tt> will work but <tt>:order => "name DESC"</tt> will not.
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 562 #
e033b5d0 » lifo 2009-07-25 Merge docrails 563 # If you do want eager load only some members of an association it is usually more natural to <tt>:include</tt> an association
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 564 # which has conditions defined on it:
565 #
566 # class Post < ActiveRecord::Base
567 # has_many :approved_comments, :class_name => 'Comment', :conditions => ['approved = ?', true]
568 # end
569 #
570 # Post.find(:all, :include => :approved_comments)
571 #
e033b5d0 » lifo 2009-07-25 Merge docrails 572 # This will load posts and eager load the +approved_comments+ association, which contains only those comments that have been approved.
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 573 #
dc37fdc4 » lifo 2008-11-02 Merge docrails. Remove unne... 574 # If you eager load an association with a specified <tt>:limit</tt> option, it will be ignored, returning all the associated objects:
575 #
576 # class Picture < ActiveRecord::Base
577 # has_many :most_recent_comments, :class_name => 'Comment', :order => 'id DESC', :limit => 10
578 # end
579 #
580 # Picture.find(:first, :include => :most_recent_comments).most_recent_comments # => returns all associated comments.
581 #
78704946 » technoweenie 2006-10-11 Restore eager condition int... 582 # When eager loaded, conditions are interpolated in the context of the model class, not the model instance. Conditions are lazily interpolated
583 # before the actual model exists.
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 584 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 585 # Eager loading is supported with polymorphic associations.
752f633b » jeremy 2008-01-04 Document that eager loading... 586 #
587 # class Address < ActiveRecord::Base
588 # belongs_to :addressable, :polymorphic => true
589 # end
590 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 591 # A call that tries to eager load the addressable model
752f633b » jeremy 2008-01-04 Document that eager loading... 592 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 593 # Address.find(:all, :include => :addressable)
b2fa70a8 » Marcel Molina 2008-01-23 Indicate in documentation t... 594 #
e033b5d0 » lifo 2009-07-25 Merge docrails 595 # This will execute one query to load the addresses and load the addressables with one query per addressable type.
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 596 # For example if all the addressables are either of class Person or Company then a total of 3 queries will be executed. The list of
597 # addressable types to load is determined on the back of the addresses loaded. This is not supported if Active Record has to fallback
19d2ff83 » miloops 2009-04-29 Calculations now use Arel t... 598 # to the previous implementation of eager loading and will raise ActiveRecord::EagerLoadPolymorphicError. The reason is that the parent
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 599 # model's type is a column value so its corresponding table name cannot be put in the +FROM+/+JOIN+ clauses of that query.
752f633b » jeremy 2008-01-04 Document that eager loading... 600 #
ed10f873 » technoweenie 2006-03-22 STI associations are now al... 601 # == Table Aliasing
602 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 603 # Active Record uses table aliasing in the case that a table is referenced multiple times in a join. If a table is referenced only once,
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 604 # the standard table name is used. The second time, the table is aliased as <tt>#{reflection_name}_#{parent_table_name}</tt>. Indexes are appended
ed10f873 » technoweenie 2006-03-22 STI associations are now al... 605 # for any more successive uses of the table name.
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 606 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 607 # Post.find :all, :joins => :comments
608 # # => SELECT ... FROM posts INNER JOIN comments ON ...
609 # Post.find :all, :joins => :special_comments # STI
610 # # => SELECT ... FROM posts INNER JOIN comments ON ... AND comments.type = 'SpecialComment'
611 # Post.find :all, :joins => [:comments, :special_comments] # special_comments is the reflection name, posts is the parent table name
612 # # => SELECT ... FROM posts INNER JOIN comments ON ... INNER JOIN comments special_comments_posts
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 613 #
ed10f873 » technoweenie 2006-03-22 STI associations are now al... 614 # Acts as tree example:
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 615 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 616 # TreeMixin.find :all, :joins => :children
617 # # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
618 # TreeMixin.find :all, :joins => {:children => :parent}
619 # # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
620 # INNER JOIN parents_mixins ...
621 # TreeMixin.find :all, :joins => {:children => {:parent => :children}}
622 # # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
623 # INNER JOIN parents_mixins ...
624 # INNER JOIN mixins childrens_mixins_2
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 625 #
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 626 # Has and Belongs to Many join tables use the same idea, but add a <tt>_join</tt> suffix:
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 627 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 628 # Post.find :all, :joins => :categories
629 # # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
630 # Post.find :all, :joins => {:categories => :posts}
631 # # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
632 # INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories
633 # Post.find :all, :joins => {:categories => {:posts => :categories}}
634 # # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
635 # INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories
636 # INNER JOIN categories_posts categories_posts_join INNER JOIN categories categories_posts_2
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 637 #
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 638 # If you wish to specify your own custom joins using a <tt>:joins</tt> option, those table names will take precedence over the eager associations:
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 639 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 640 # Post.find :all, :joins => :comments, :joins => "inner join comments ..."
641 # # => SELECT ... FROM posts INNER JOIN comments_posts ON ... INNER JOIN comments ...
642 # Post.find :all, :joins => [:comments, :special_comments], :joins => "inner join comments ..."
643 # # => SELECT ... FROM posts INNER JOIN comments comments_posts ON ...
644 # INNER JOIN comments special_comments_posts ...
ed10f873 » technoweenie 2006-03-22 STI associations are now al... 645 # INNER JOIN comments ...
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 646 #
ed10f873 » technoweenie 2006-03-22 STI associations are now al... 647 # Table aliases are automatically truncated according to the maximum length of table identifiers according to the specific database.
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 648 #
db045dbb » dhh 2004-11-23 Initial 649 # == Modules
650 #
651 # By default, associations will look for objects within the current module scope. Consider:
652 #
653 # module MyApplication
654 # module Business
655 # class Firm < ActiveRecord::Base
656 # has_many :clients
657 # end
658 #
0432d151 » lifo 2008-07-16 Merge with docrails. Comment 659 # class Client < ActiveRecord::Base; end
db045dbb » dhh 2004-11-23 Initial 660 # end
661 # end
662 #
0432d151 » lifo 2008-07-16 Merge with docrails. Comment 663 # When <tt>Firm#clients</tt> is called, it will in turn call <tt>MyApplication::Business::Client.find_all_by_firm_id(firm.id)</tt>.
664 # If you want to associate with a class in another module scope, this can be done by specifying the complete class name.
665 # Example:
db045dbb » dhh 2004-11-23 Initial 666 #
667 # module MyApplication
668 # module Business
669 # class Firm < ActiveRecord::Base; end
670 # end
671 #
672 # module Billing
673 # class Account < ActiveRecord::Base
674 # belongs_to :firm, :class_name => "MyApplication::Business::Firm"
675 # end
676 # end
677 # end
678 #
e033b5d0 » lifo 2009-07-25 Merge docrails 679 # == Bi-directional associations
680 #
681 # When you specify an association there is usually an association on the associated model that specifies the same
682 # relationship in reverse. For example, with the following models:
683 #
684 # class Dungeon < ActiveRecord::Base
685 # has_many :traps
686 # has_one :evil_wizard
687 # end
688 #
689 # class Trap < ActiveRecord::Base
690 # belongs_to :dungeon
691 # end
692 #
693 # class EvilWizard < ActiveRecord::Base
694 # belongs_to :dungeon
695 # end
696 #
697 # The +traps+ association on +Dungeon+ and the the +dungeon+ association on +Trap+ are the inverse of each other and the
698 # inverse of the +dungeon+ association on +EvilWizard+ is the +evil_wizard+ association on +Dungeon+ (and vice-versa). By default,
699 # +ActiveRecord+ doesn't do know anything about these inverse relationships and so no object loading optimisation is possible. For example:
700 #
701 # d = Dungeon.first
702 # t = d.traps.first
703 # d.level == t.dungeon.level # => true
704 # d.level = 10
705 # d.level == t.dungeon.level # => false
706 #
3de59e91 » miloops 2009-07-31 Merge commit 'rails/master' 707 # The +Dungeon+ instances +d+ and <tt>t.dungeon</tt> in the above example refer to the same object data from the database, but are
e033b5d0 » lifo 2009-07-25 Merge docrails 708 # actually different in-memory copies of that data. Specifying the <tt>:inverse_of</tt> option on associations lets you tell
709 # +ActiveRecord+ about inverse relationships and it will optimise object loading. For example, if we changed our model definitions to:
710 #
711 # class Dungeon < ActiveRecord::Base
712 # has_many :traps, :inverse_of => :dungeon
713 # has_one :evil_wizard, :inverse_of => :dungeon
714 # end
715 #
716 # class Trap < ActiveRecord::Base
717 # belongs_to :dungeon, :inverse_of => :traps
718 # end
719 #
720 # class EvilWizard < ActiveRecord::Base
721 # belongs_to :dungeon, :inverse_of => :evil_wizard
722 # end
723 #
724 # Then, from our code snippet above, +d+ and <tt>t.dungeon</tt> are actually the same in-memory instance and our final <tt>d.level == t.dungeon.level</tt>
725 # will return +true+.
726 #
727 # There are limitations to <tt>:inverse_of</tt> support:
728 #
729 # * does not work with <tt>:through</tt> associations.
730 # * does not work with <tt>:polymorphic</tt> associations.
731 # * for +belongs_to+ associations +has_many+ inverse associations are ignored.
732 #
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 733 # == Type safety with <tt>ActiveRecord::AssociationTypeMismatch</tt>
db045dbb » dhh 2004-11-23 Initial 734 #
735 # If you attempt to assign an object to an association that doesn't match the inferred or specified <tt>:class_name</tt>, you'll
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 736 # get an <tt>ActiveRecord::AssociationTypeMismatch</tt>.
db045dbb » dhh 2004-11-23 Initial 737 #
738 # == Options
739 #
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 740 # All of the association macros can be specialized through options. This makes cases more complex than the simple and guessable ones
db045dbb » dhh 2004-11-23 Initial 741 # possible.
742 module ClassMethods
6e754551 » lifo 2008-07-28 Merge docrails changes 743 # Specifies a one-to-many association. The following methods for retrieval and query of
744 # collections of associated objects will be added:
745 #
746 # [collection(force_reload = false)]
747 # Returns an array of all the associated objects.
db045dbb » dhh 2004-11-23 Initial 748 # An empty array is returned if none are found.
6e754551 » lifo 2008-07-28 Merge docrails changes 749 # [collection<<(object, ...)]
750 # Adds one or more objects to the collection by setting their foreign keys to the collection's primary key.
751 # [collection.delete(object, ...)]
752 # Removes one or more objects from the collection by setting their foreign keys to +NULL+.
a03e2b35 » lifo 2008-10-21 Merge with docrails. Also a... 753 # Objects will be in addition destroyed if they're associated with <tt>:dependent => :destroy</tt>,
754 # and deleted if they're associated with <tt>:dependent => :delete_all</tt>.
6e754551 » lifo 2008-07-28 Merge docrails changes 755 # [collection=objects]
756 # Replaces the collections content by deleting and adding objects as appropriate.
757 # [collection_singular_ids]
758 # Returns an array of the associated objects' ids
759 # [collection_singular_ids=ids]
760 # Replace the collection with the objects identified by the primary keys in +ids+
761 # [collection.clear]
762 # Removes every object from the collection. This destroys the associated objects if they
763 # are associated with <tt>:dependent => :destroy</tt>, deletes them directly from the
764 # database if <tt>:dependent => :delete_all</tt>, otherwise sets their foreign keys to +NULL+.
765 # [collection.empty?]
766 # Returns +true+ if there are no associated objects.
767 # [collection.size]
768 # Returns the number of associated objects.
769 # [collection.find(...)]
770 # Finds an associated object according to the same rules as ActiveRecord::Base.find.
c3f53f41 » lifo 2008-12-19 Merge docrails 771 # [collection.exists?(...)]
6e754551 » lifo 2008-07-28 Merge docrails changes 772 # Checks whether an associated object with the given conditions exists.
773 # Uses the same rules as ActiveRecord::Base.exists?.
774 # [collection.build(attributes = {}, ...)]
775 # Returns one or more new objects of the collection type that have been instantiated
776 # with +attributes+ and linked to this object through a foreign key, but have not yet
777 # been saved. <b>Note:</b> This only works if an associated object already exists, not if
778 # it's +nil+!
779 # [collection.create(attributes = {})]
780 # Returns a new object of the collection type that has been instantiated
781 # with +attributes+, linked to this object through a foreign key, and that has already
782 # been saved (if it passed the validation). <b>Note:</b> This only works if an associated
783 # object already exists, not if it's +nil+!
784 #
785 # (*Note*: +collection+ is replaced with the symbol passed as the first argument, so
786 # <tt>has_many :clients</tt> would add among others <tt>clients.empty?</tt>.)
787 #
788 # === Example
db045dbb » dhh 2004-11-23 Initial 789 #
6ef35461 » lifo 2008-09-03 Merge docrails 790 # Example: A Firm class declares <tt>has_many :clients</tt>, which will add:
791 # * <tt>Firm#clients</tt> (similar to <tt>Clients.find :all, :conditions => ["firm_id = ?", id]</tt>)
db045dbb » dhh 2004-11-23 Initial 792 # * <tt>Firm#clients<<</tt>
793 # * <tt>Firm#clients.delete</tt>
bfe6a759 » dhh 2005-06-15 Added actual database-chang... 794 # * <tt>Firm#clients=</tt>
cb0837a2 » dhh 2006-10-08 Doc fixes (closes #6325) 795 # * <tt>Firm#client_ids</tt>
bfe6a759 » dhh 2005-06-15 Added actual database-chang... 796 # * <tt>Firm#client_ids=</tt>
db045dbb » dhh 2004-11-23 Initial 797 # * <tt>Firm#clients.clear</tt>
798 # * <tt>Firm#clients.empty?</tt> (similar to <tt>firm.clients.size == 0</tt>)
799 # * <tt>Firm#clients.size</tt> (similar to <tt>Client.count "firm_id = #{id}"</tt>)
c1611a70 » dhh 2005-04-18 Updated documentation here ... 800 # * <tt>Firm#clients.find</tt> (similar to <tt>Client.find(id, :conditions => "firm_id = #{id}")</tt>)
c3f53f41 » lifo 2008-12-19 Merge docrails 801 # * <tt>Firm#clients.exists?(:name => 'ACME')</tt> (similar to <tt>Client.exists?(:name => 'ACME', :firm_id => firm.id)</tt>)
db045dbb » dhh 2004-11-23 Initial 802 # * <tt>Firm#clients.build</tt> (similar to <tt>Client.new("firm_id" => id)</tt>)
1d4d7217 » dhh 2005-06-21 Fixed docs #856 803 # * <tt>Firm#clients.create</tt> (similar to <tt>c = Client.new("firm_id" => id); c.save; c</tt>)
db045dbb » dhh 2004-11-23 Initial 804 # The declaration can also include an options hash to specialize the behavior of the association.
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 805 #
6e754551 » lifo 2008-07-28 Merge docrails changes 806 # === Supported options
807 # [:class_name]
808 # Specify the class name of the association. Use it only if that name can't be inferred
dc4eec11 » lifo 2008-05-09 Merge docrails: 809 # from the association name. So <tt>has_many :products</tt> will by default be linked to the Product class, but
810 # if the real class name is SpecialProduct, you'll have to specify it with this option.
6e754551 » lifo 2008-07-28 Merge docrails changes 811 # [:conditions]
812 # Specify the conditions that the associated objects must meet in order to be included as a +WHERE+
c23c9bd1 » technoweenie 2008-03-21 Allow association scoping f... 813 # SQL fragment, such as <tt>price > 5 AND name LIKE 'B%'</tt>. Record creations from the association are scoped if a hash
814 # is used. <tt>has_many :posts, :conditions => {:published => true}</tt> will create published posts with <tt>@blog.posts.create</tt>
815 # or <tt>@blog.posts.build</tt>.
6e754551 » lifo 2008-07-28 Merge docrails changes 816 # [:order]
817 # Specify the order in which the associated objects are returned as an <tt>ORDER BY</tt> SQL fragment,
dc4eec11 » lifo 2008-05-09 Merge docrails: 818 # such as <tt>last_name, first_name DESC</tt>.
6e754551 » lifo 2008-07-28 Merge docrails changes 819 # [:foreign_key]
820 # Specify the foreign key used for the association. By default this is guessed to be the name
dc4eec11 » lifo 2008-05-09 Merge docrails: 821 # of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_many+ association will use "person_id"
822 # as the default <tt>:foreign_key</tt>.
6e754551 » lifo 2008-07-28 Merge docrails changes 823 # [:primary_key]
824 # Specify the method that returns the primary key used for the association. By default this is +id+.
825 # [:dependent]
826 # If set to <tt>:destroy</tt> all the associated objects are destroyed
dc4eec11 » lifo 2008-05-09 Merge docrails: 827 # alongside this object by calling their +destroy+ method. If set to <tt>:delete_all</tt> all associated
828 # objects are deleted *without* calling their +destroy+ method. If set to <tt>:nullify</tt> all associated
829 # objects' foreign keys are set to +NULL+ *without* calling their +save+ callbacks. *Warning:* This option is ignored when also using
830 # the <tt>:through</tt> option.
6e754551 » lifo 2008-07-28 Merge docrails changes 831 # [:finder_sql]
832 # Specify a complete SQL statement to fetch the association. This is a good way to go for complex
a8eea0b0 » dhh 2005-10-26 Fix docs (closes #2491) 833 # associations that depend on multiple tables. Note: When this option is used, +find_in_collection+ is _not_ added.
6e754551 » lifo 2008-07-28 Merge docrails changes 834 # [:counter_sql]
835 # Specify a complete SQL statement to fetch the size of the association. If <tt>:finder_sql</tt> is
7143d801 » Marcel Molina 2007-11-07 Smattering of grammatical f... 836 # specified but not <tt>:counter_sql</tt>, <tt>:counter_sql</tt> will be generated by replacing <tt>SELECT ... FROM</tt> with <tt>SELECT COUNT(*) FROM</tt>.
6e754551 » lifo 2008-07-28 Merge docrails changes 837 # [:extend]
838 # Specify a named module for extending the proxy. See "Association extensions".
839 # [:include]
840 # Specify second-order associations that should be eager loaded when the collection is loaded.
841 # [:group]
842 # An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
97403ad5 » miloops 2008-11-21 Add :having option to find,... 843 # [:having]
844 # Combined with +:group+ this can be used to filter the records that a <tt>GROUP BY</tt> returns. Uses the <tt>HAVING</tt> SQL-clause.
6e754551 » lifo 2008-07-28 Merge docrails changes 845 # [:limit]
846 # An integer determining the limit on the number of rows that should be returned.
847 # [:offset]
848 # An integer determining the offset from where the rows should be fetched. So at 5, it would skip the first 4 rows.
849 # [:select]
850 # By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if you, for example, want to do a join
3351d299 » indirect 2008-05-31 Add has_many :primary_key o... 851 # but not include the joined columns. Do not forget to include the primary and foreign keys, otherwise it will raise an error.
6e754551 » lifo 2008-07-28 Merge docrails changes 852 # [:as]
853 # Specifies a polymorphic interface (See <tt>belongs_to</tt>).
854 # [:through]
855 # Specifies a Join Model through which to perform the query. Options for <tt>:class_name</tt> and <tt>:foreign_key</tt>
9f51eb24 » jeremy 2007-05-22 Fix :through docs wrecked u... 856 # are ignored, as the association uses the source reflection. You can only use a <tt>:through</tt> query through a <tt>belongs_to</tt>
00d6c766 » dasil003 2009-08-09 Enable has_many :through fo... 857 # <tt>has_one</tt> or <tt>has_many</tt> association on the join model.
6e754551 » lifo 2008-07-28 Merge docrails changes 858 # [:source]
859 # Specifies the source association name used by <tt>has_many :through</tt> queries. Only use it if the name cannot be
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 860 # inferred from the association. <tt>has_many :subscribers, :through => :subscriptions</tt> will look for either <tt>:subscribers</tt> or
dc4eec11 » lifo 2008-05-09 Merge docrails: 861 # <tt>:subscriber</tt> on Subscription, unless a <tt>:source</tt> is given.
6e754551 » lifo 2008-07-28 Merge docrails changes 862 # [:source_type]
863 # Specifies type of the source association used by <tt>has_many :through</tt> queries where the source
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 864 # association is a polymorphic +belongs_to+.
6e754551 » lifo 2008-07-28 Merge docrails changes 865 # [:uniq]
866 # If true, duplicates will be omitted from the collection. Useful in conjunction with <tt>:through</tt>.
867 # [:readonly]
868 # If true, all the associated objects are readonly through the association.
869 # [:validate]
870 # If false, don't validate the associated objects when saving the parent object. true by default.
ec8f0458 » alloy 2009-01-31 Add support for nested obje... Comment 871 # [:autosave]
872 # If true, always save any loaded members and destroy members marked for destruction, when saving the parent object. Off by default.
e033b5d0 » lifo 2009-07-25 Merge docrails 873 # [:inverse_of]
3de59e91 » miloops 2009-07-31 Merge commit 'rails/master' 874 # Specifies the name of the <tt>belongs_to</tt> association on the associated object that is the inverse of this <tt>has_many</tt>
875 # association. Does not work in combination with <tt>:through</tt> or <tt>:as</tt> options.
e033b5d0 » lifo 2009-07-25 Merge docrails 876 # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional assocations for more detail.
ec8f0458 » alloy 2009-01-31 Add support for nested obje... Comment 877 #
db045dbb » dhh 2004-11-23 Initial 878 # Option examples:
879 # has_many :comments, :order => "posted_on"
49c801b7 » dhh 2005-11-06 Added :include as an option... 880 # has_many :comments, :include => :author
db045dbb » dhh 2004-11-23 Initial 881 # has_many :people, :class_name => "Person", :conditions => "deleted = 0", :order => "name"
57565b35 » NZKoz 2006-03-09 format fix for locking [Mic... 882 # has_many :tracks, :order => "position", :dependent => :destroy
883 # has_many :comments, :dependent => :nullify
2597bd69 » technoweenie 2006-03-27 documentation for polymorph... 884 # has_many :tags, :as => :taggable
dfa78663 » jeremy 2008-02-12 Introduce the :readonly opt... 885 # has_many :reports, :readonly => true
38bae0a9 » technoweenie 2006-03-24 Change has_many :through to... 886 # has_many :subscribers, :through => :subscriptions, :source => :user
db045dbb » dhh 2004-11-23 Initial 887 # has_many :subscribers, :class_name => "Person", :finder_sql =>
888 # 'SELECT DISTINCT people.* ' +
889 # 'FROM people p, post_subscriptions ps ' +
890 # 'WHERE ps.post_id = #{id} AND ps.person_id = p.id ' +
891 # 'ORDER BY p.first_name'
c8dd66fd » dhh 2005-11-06 Made association extensions... 892 def has_many(association_id, options = {}, &extension)
6abda696 » dhh 2005-12-02 Added preliminary support f... 893 reflection = create_has_many_reflection(association_id, options, &extension)
894 configure_dependency_for_has_many(reflection)
f6b12c11 » lifo 2008-04-05 Refactor HasManyThroughAsso... 895 add_association_callbacks(reflection.name, reflection.options)
896
6abda696 » dhh 2005-12-02 Added preliminary support f... 897 if options[:through]
f6b12c11 » lifo 2008-04-05 Refactor HasManyThroughAsso... 898 collection_accessor_methods(reflection, HasManyThroughAssociation)
6abda696 » dhh 2005-12-02 Added preliminary support f... 899 else
900 collection_accessor_methods(reflection, HasManyAssociation)
db045dbb » dhh 2004-11-23 Initial 901 end
902 end
903
6e754551 » lifo 2008-07-28 Merge docrails changes 904 # Specifies a one-to-one association with another class. This method should only be used
905 # if the other class contains the foreign key. If the current class contains the foreign key,
906 # then you should use +belongs_to+ instead. See also ActiveRecord::Associations::ClassMethods's overview
907 # on when to use has_one and when to use belongs_to.
908 #
909 # The following methods for retrieval and query of a single associated object will be added:
910 #
911 # [association(force_reload = false)]
912 # Returns the associated object. +nil+ is returned if none is found.
913 # [association=(associate)]
914 # Assigns the associate object, extracts the primary key, sets it as the foreign key,
db045dbb » dhh 2004-11-23 Initial 915 # and saves the associate object.
6e754551 » lifo 2008-07-28 Merge docrails changes 916 # [build_association(attributes = {})]
917 # Returns a new object of the associated type that has been instantiated
918 # with +attributes+ and linked to this object through a foreign key, but has not
919 # yet been saved. <b>Note:</b> This ONLY works if an association already exists.
920 # It will NOT work if the association is +nil+.
921 # [create_association(attributes = {})]
922 # Returns a new object of the associated type that has been instantiated
923 # with +attributes+, linked to this object through a foreign key, and that
924 # has already been saved (if it passed the validation).
925 #
926 # (+association+ is replaced with the symbol passed as the first argument, so
927 # <tt>has_one :manager</tt> would add among others <tt>manager.nil?</tt>.)
db045dbb » dhh 2004-11-23 Initial 928 #
6e754551 » lifo 2008-07-28 Merge docrails changes 929 # === Example
930 #
931 # An Account class declares <tt>has_one :beneficiary</tt>, which will add:
3dfa56cc » dhh 2005-06-26 Updated all references to t... 932 # * <tt>Account#beneficiary</tt> (similar to <tt>Beneficiary.find(:first, :conditions => "account_id = #{id}")</tt>)
db045dbb » dhh 2004-11-23 Initial 933 # * <tt>Account#beneficiary=(beneficiary)</tt> (similar to <tt>beneficiary.account_id = account.id; beneficiary.save</tt>)
3b9e90a4 » dhh 2005-04-11 Moved build_association and... 934 # * <tt>Account#build_beneficiary</tt> (similar to <tt>Beneficiary.new("account_id" => id)</tt>)
935 # * <tt>Account#create_beneficiary</tt> (similar to <tt>b = Beneficiary.new("account_id" => id); b.save; b</tt>)
936 #
6e754551 » lifo 2008-07-28 Merge docrails changes 937 # === Options
938 #
db045dbb » dhh 2004-11-23 Initial 939 # The declaration can also include an options hash to specialize the behavior of the association.
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 940 #
db045dbb » dhh 2004-11-23 Initial 941 # Options are:
6e754551 » lifo 2008-07-28 Merge docrails changes 942 # [:class_name]
943 # Specify the class name of the association. Use it only if that name can't be inferred
dc4eec11 » lifo 2008-05-09 Merge docrails: 944 # from the association name. So <tt>has_one :manager</tt> will by default be linked to the Manager class, but
945 # if the real class name is Person, you'll have to specify it with this option.
6e754551 » lifo 2008-07-28 Merge docrails changes 946 # [:conditions]
947 # Specify the conditions that the associated object must meet in order to be included as a +WHERE+
4168f876 » Luciano G Panaro 2009-09-26 Make has_one with :conditio... 948 # SQL fragment, such as <tt>rank = 5</tt>. Record creation from the association is scoped if a hash
949 # is used. <tt>has_one :account, :conditions => {:enabled => true}</tt> will create an enabled account with <tt>@company.create_account</tt>
950 # or <tt>@company.build_account</tt>.
6e754551 » lifo 2008-07-28 Merge docrails changes 951 # [:order]
952 # Specify the order in which the associated objects are returned as an <tt>ORDER BY</tt> SQL fragment,
dc4eec11 » lifo 2008-05-09 Merge docrails: 953 # such as <tt>last_name, first_name DESC</tt>.
6e754551 » lifo 2008-07-28 Merge docrails changes 954 # [:dependent]
955 # If set to <tt>:destroy</tt>, the associated object is destroyed when this object is. If set to
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 956 # <tt>:delete</tt>, the associated object is deleted *without* calling its destroy method. If set to <tt>:nullify</tt>, the associated
957 # object's foreign key is set to +NULL+. Also, association is assigned.
6e754551 » lifo 2008-07-28 Merge docrails changes 958 # [:foreign_key]
959 # Specify the foreign key used for the association. By default this is guessed to be the name
dc4eec11 » lifo 2008-05-09 Merge docrails: 960 # of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_one+ association will use "person_id"
961 # as the default <tt>:foreign_key</tt>.
6e754551 » lifo 2008-07-28 Merge docrails changes 962 # [:primary_key]
963 # Specify the method that returns the primary key used for the association. By default this is +id+.
964 # [:include]
965 # Specify second-order associations that should be eager loaded when this object is loaded.
966 # [:as]
967 # Specifies a polymorphic interface (See <tt>belongs_to</tt>).
968 # [:select]
969 # By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if, for example, you want to do a join
8d0b4fa3 » josevalim 2008-05-23 Added :select option to has... 970 # but not include the joined columns. Do not forget to include the primary and foreign keys, otherwise it will raise an error.
6e754551 » lifo 2008-07-28 Merge docrails changes 971 # [:through]
972 # Specifies a Join Model through which to perform the query. Options for <tt>:class_name</tt> and <tt>:foreign_key</tt>
19d2ff83 » miloops 2009-04-29 Calculations now use Arel t... 973 # are ignored, as the association uses the source reflection. You can only use a <tt>:through</tt> query through a
273b21fa » technoweenie 2008-03-21 Add has_one :through suppor... 974 # <tt>has_one</tt> or <tt>belongs_to</tt> association on the join model.
6e754551 » lifo 2008-07-28 Merge docrails changes 975 # [:source]
976 # Specifies the source association name used by <tt>has_one :through</tt> queries. Only use it if the name cannot be
273b21fa » technoweenie 2008-03-21 Add has_one :through suppor... 977 # inferred from the association. <tt>has_one :favorite, :through => :favorites</tt> will look for a
5cda000b » dhh 2009-02-27 Fixed that autosave should ... Comment 978 # <tt>:favorite</tt> on Favorite, unless a <tt>:source</tt> is given.
6e754551 » lifo 2008-07-28 Merge docrails changes 979 # [:source_type]
980 # Specifies type of the source association used by <tt>has_one :through</tt> queries where the source
5cda000b » dhh 2009-02-27 Fixed that autosave should ... Comment 981 # association is a polymorphic +belongs_to+.
6e754551 » lifo 2008-07-28 Merge docrails changes 982 # [:readonly]
983 # If true, the associated object is readonly through the association.
984 # [:validate]
985 # If false, don't validate the associated object when saving the parent object. +false+ by default.
ec8f0458 » alloy 2009-01-31 Add support for nested obje... Comment 986 # [:autosave]
987 # If true, always save the associated object or destroy it if marked for destruction, when saving the parent object. Off by default.
e033b5d0 » lifo 2009-07-25 Merge docrails 988 # [:inverse_of]
3de59e91 » miloops 2009-07-31 Merge commit 'rails/master' 989 # Specifies the name of the <tt>belongs_to</tt> association on the associated object that is the inverse of this <tt>has_one</tt>
990 # association. Does not work in combination with <tt>:through</tt> or <tt>:as</tt> options.
e033b5d0 » lifo 2009-07-25 Merge docrails 991 # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional assocations for more detail.
dfa78663 » jeremy 2008-02-12 Introduce the :readonly opt... 992 #
db045dbb » dhh 2004-11-23 Initial 993 # Option examples:
57565b35 » NZKoz 2006-03-09 format fix for locking [Mic... 994 # has_one :credit_card, :dependent => :destroy # destroys the associated credit card
7143d801 » Marcel Molina 2007-11-07 Smattering of grammatical f... 995 # has_one :credit_card, :dependent => :nullify # updates the associated records foreign key value to NULL rather than destroying it
db045dbb » dhh 2004-11-23 Initial 996 # has_one :last_comment, :class_name => "Comment", :order => "posted_on"
997 # has_one :project_manager, :class_name => "Person", :conditions => "role = 'project_manager'"
21399219 » technoweenie 2006-05-22 Add docs for the :as option... 998 # has_one :attachment, :as => :attachable
dfa78663 » jeremy 2008-02-12 Introduce the :readonly opt... 999 # has_one :boss, :readonly => :true
273b21fa » technoweenie 2008-03-21 Add has_one :through suppor... 1000 # has_one :club, :through => :membership
1001 # has_one :primary_address, :through => :addressables, :conditions => ["addressable.primary = ?", true], :source => :addressable
db045dbb » dhh 2004-11-23 Initial 1002 def has_one(association_id, options = {})
273b21fa » technoweenie 2008-03-21 Add has_one :through suppor... 1003 if options[:through]
1004 reflection = create_has_one_through_reflection(association_id, options)
1005 association_accessor_methods(reflection, ActiveRecord::Associations::HasOneThroughAssociation)
1006 else
1007 reflection = create_has_one_reflection(association_id, options)
1008 association_accessor_methods(reflection, HasOneAssociation)
1009 association_constructor_method(:build, reflection, HasOneAssociation)
1010 association_constructor_method(:create, reflection, HasOneAssociation)
1011 configure_dependency_for_has_one(reflection)
1012 end
db045dbb » dhh 2004-11-23 Initial 1013 end
1014
6e754551 » lifo 2008-07-28 Merge docrails changes 1015 # Specifies a one-to-one association with another class. This method should only be used
1016 # if this class contains the foreign key. If the other class contains the foreign key,
1017 # then you should use +has_one+ instead. See also ActiveRecord::Associations::ClassMethods's overview
1018 # on when to use +has_one+ and when to use +belongs_to+.
1019 #
1020 # Methods will be added for retrieval and query for a single associated object, for which
1021 # this object holds an id:
1022 #
1023 # [association(force_reload = false)]
1024 # Returns the associated object. +nil+ is returned if none is found.
1025 # [association=(associate)]
1026 # Assigns the associate object, extracts the primary key, and sets it as the foreign key.
1027 # [build_association(attributes = {})]
1028 # Returns a new object of the associated type that has been instantiated
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 1029 # with +attributes+ and linked to this object through a foreign key, but has not yet been saved.
6e754551 » lifo 2008-07-28 Merge docrails changes 1030 # [create_association(attributes = {})]
1031 # Returns a new object of the associated type that has been instantiated
1032 # with +attributes+, linked to this object through a foreign key, and that
1033 # has already been saved (if it passed the validation).
1034 #
1035 # (+association+ is replaced with the symbol passed as the first argument, so
1036 # <tt>belongs_to :author</tt> would add among others <tt>author.nil?</tt>.)
db045dbb » dhh 2004-11-23 Initial 1037 #
6e754551 » lifo 2008-07-28 Merge docrails changes 1038 # === Example
1039 #
1040 # A Post class declares <tt>belongs_to :author</tt>, which will add:
db045dbb » dhh 2004-11-23 Initial 1041 # * <tt>Post#author</tt> (similar to <tt>Author.find(author_id)</tt>)
1042 # * <tt>Post#author=(author)</tt> (similar to <tt>post.author_id = author.id</tt>)
1043 # * <tt>Post#author?</tt> (similar to <tt>post.author == some_author</tt>)
1d4d7217 » dhh 2005-06-21 Fixed docs #856 1044 # * <tt>Post#build_author</tt> (similar to <tt>post.author = Author.new</tt>)
1045 # * <tt>Post#create_author</tt> (similar to <tt>post.author = Author.new; post.author.save; post.author</tt>)
db045dbb » dhh 2004-11-23 Initial 1046 # The declaration can also include an options hash to specialize the behavior of the association.
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 1047 #
6e754551 » lifo 2008-07-28 Merge docrails changes 1048 # === Options
1049 #
1050 # [:class_name]
1051 # Specify the class name of the association. Use it only if that name can't be inferred
dc4eec11 » lifo 2008-05-09 Merge docrails: 1052 # from the association name. So <tt>has_one :author</tt> will by default be linked to the Author class, but
1053 # if the real class name is Person, you'll have to specify it with this option.
6e754551 » lifo 2008-07-28 Merge docrails changes 1054 # [:conditions]
1055 # Specify the conditions that the associated object must meet in order to be included as a +WHERE+
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 1056 # SQL fragment, such as <tt>authorized = 1</tt>.
6e754551 » lifo 2008-07-28 Merge docrails changes 1057 # [:select]
1058 # By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if, for example, you want to do a join
8d0b4fa3 » josevalim 2008-05-23 Added :select option to has... 1059 # but not include the joined columns. Do not forget to include the primary and foreign keys, otherwise it will raise an error.
6e754551 » lifo 2008-07-28 Merge docrails changes 1060 # [:foreign_key]
1061 # Specify the foreign key used for the association. By default this is guessed to be the name
dc4eec11 » lifo 2008-05-09 Merge docrails: 1062 # of the association with an "_id" suffix. So a class that defines a <tt>belongs_to :person</tt> association will use
1063 # "person_id" as the default <tt>:foreign_key</tt>. Similarly, <tt>belongs_to :favorite_person, :class_name => "Person"</tt>
1064 # will use a foreign key of "favorite_person_id".
1c11437a » szimek 2009-07-15 Add primary_key option to b... Comment 1065 # [:primary_key]
1066 # Specify the method that returns the primary key of associated object used for the association. By default this is id.
6e754551 » lifo 2008-07-28 Merge docrails changes 1067 # [:dependent]
1068 # If set to <tt>:destroy</tt>, the associated object is destroyed when this object is. If set to
16b129a6 » jeremy 2008-01-18 belongs_to supports :depend... 1069 # <tt>:delete</tt>, the associated object is deleted *without* calling its destroy method. This option should not be specified when
1070 # <tt>belongs_to</tt> is used in conjunction with a <tt>has_many</tt> relationship on another class because of the potential to leave
1071 # orphaned records behind.
6e754551 » lifo 2008-07-28 Merge docrails changes 1072 # [:counter_cache]
1073 # Caches the number of belonging objects on the associate class through the use of +increment_counter+
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 1074 # and +decrement_counter+. The counter cache is incremented when an object of this class is created and decremented when it's
dc4eec11 » lifo 2008-05-09 Merge docrails: 1075 # destroyed. This requires that a column named <tt>#{table_name}_count</tt> (such as +comments_count+ for a belonging Comment class)
1076 # is used on the associate class (such as a Post class). You can also specify a custom counter cache column by providing
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 1077 # a column name instead of a +true+/+false+ value to this option (e.g., <tt>:counter_cache => :my_custom_counter</tt>.)
dc4eec11 » lifo 2008-05-09 Merge docrails: 1078 # Note: Specifying a counter cache will add it to that model's list of readonly attributes using +attr_readonly+.
6e754551 » lifo 2008-07-28 Merge docrails changes 1079 # [:include]
1080 # Specify second-order associations that should be eager loaded when this object is loaded.
1081 # [:polymorphic]
1082 # Specify this association is a polymorphic association by passing +true+.
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 1083 # Note: If you've enabled the counter cache, then you may want to add the counter cache attribute
dc4eec11 » lifo 2008-05-09 Merge docrails: 1084 # to the +attr_readonly+ list in the associated classes (e.g. <tt>class Post; attr_readonly :comments_count; end</tt>).
6e754551 » lifo 2008-07-28 Merge docrails changes 1085 # [:readonly]
1086 # If true, the associated object is readonly through the association.
1087 # [:validate]
1088 # If false, don't validate the associated objects when saving the parent object. +false+ by default.
ec8f0458 » alloy 2009-01-31 Add support for nested obje... Comment 1089 # [:autosave]
1090 # If true, always save the associated object or destroy it if marked for destruction, when saving the parent object. Off by default.
abb899c5 » dhh 2009-04-16 Added :touch option to belo... Comment 1091 # [:touch]
1092 # If true, the associated object will be touched (the updated_at/on attributes set to now) when this record is either saved or
1093 # destroyed. If you specify a symbol, that attribute will be updated with the current time instead of the updated_at/on attribute.
e033b5d0 » lifo 2009-07-25 Merge docrails 1094 # [:inverse_of]
3de59e91 » miloops 2009-07-31 Merge commit 'rails/master' 1095 # Specifies the name of the <tt>has_one</tt> or <tt>has_many</tt> association on the associated object that is the inverse of this <tt>belongs_to</tt>
1096 # association. Does not work in combination with the <tt>:polymorphic</tt> options.
e033b5d0 » lifo 2009-07-25 Merge docrails 1097 # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional assocations for more detail.
db045dbb » dhh 2004-11-23 Initial 1098 #
1099 # Option examples:
1100 # belongs_to :firm, :foreign_key => "client_of"
1c11437a » szimek 2009-07-15 Add primary_key option to b... Comment 1101 # belongs_to :person, :primary_key => "name", :foreign_key => "person_name"
db045dbb » dhh 2004-11-23 Initial 1102 # belongs_to :author, :class_name => "Person", :foreign_key => "author_id"
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 1103 # belongs_to :valid_coupon, :class_name => "Coupon", :foreign_key => "coupon_id",
db045dbb » dhh 2004-11-23 Initial 1104 # :conditions => 'discounts > #{payments_count}'
2597bd69 » technoweenie 2006-03-27 documentation for polymorph... 1105 # belongs_to :attachable, :polymorphic => true
dfa78663 » jeremy 2008-02-12 Introduce the :readonly opt... 1106 # belongs_to :project, :readonly => true
54213dad » dhh 2008-03-19 Docfixes (closes #11356, #1... 1107 # belongs_to :post, :counter_cache => true
abb899c5 » dhh 2009-04-16 Added :touch option to belo... Comment 1108 # belongs_to :company, :touch => true
1109 # belongs_to :company, :touch => :employees_last_updated_at
823554ea » dhh 2005-01-15 Added support for associati... 1110 def belongs_to(association_id, options = {})
6abda696 » dhh 2005-12-02 Added preliminary support f... 1111 reflection = create_belongs_to_reflection(association_id, options)
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 1112
6abda696 » dhh 2005-12-02 Added preliminary support f... 1113 if reflection.options[:polymorphic]
1114 association_accessor_methods(reflection, BelongsToPolymorphicAssociation)
57b7532b » dhh 2005-12-01 Work-in progress for provid... 1115 else
6abda696 » dhh 2005-12-02 Added preliminary support f... 1116 association_accessor_methods(reflection, BelongsToAssociation)
1117 association_constructor_method(:build, reflection, BelongsToAssociation)
1118 association_constructor_method(:create, reflection, BelongsToAssociation)
57b7532b » dhh 2005-12-01 Work-in progress for provid... 1119 end
964b67dd » jamis 2006-03-04 Make counter_cache work wit... 1120
abb899c5 » dhh 2009-04-16 Added :touch option to belo... Comment 1121 add_counter_cache_callbacks(reflection) if options[:counter_cache]
1122 add_touch_callbacks(reflection, options[:touch]) if options[:touch]
16b129a6 » jeremy 2008-01-18 belongs_to supports :depend... 1123
1124 configure_dependency_for_belongs_to(reflection)
823554ea » dhh 2005-01-15 Added support for associati... 1125 end
1126
6e754551 » lifo 2008-07-28 Merge docrails changes 1127 # Specifies a many-to-many relationship with another class. This associates two classes via an
1128 # intermediate join table. Unless the join table is explicitly specified as an option, it is
1129 # guessed using the lexical order of the class names. So a join between Developer and Project
dc4eec11 » lifo 2008-05-09 Merge docrails: 1130 # will give the default join table name of "developers_projects" because "D" outranks "P". Note that this precedence
1131 # is calculated using the <tt><</tt> operator for String. This means that if the strings are of different lengths,
56c55354 » technoweenie 2007-01-15 [DOC] clear up some ambigui... 1132 # and the strings are equal when compared up to the shortest length, then the longer string is considered of higher
dc4eec11 » lifo 2008-05-09 Merge docrails: 1133 # lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers"
1134 # to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes",
1135 # but it in fact generates a join table name of "paper_boxes_papers". Be aware of this caveat, and use the
1136 # custom <tt>:join_table</tt> option if you need to.
db045dbb » dhh 2004-11-23 Initial 1137 #
96d61055 » lifo 2009-02-05 Merge docrails along with t... 1138 # The join table should not have a primary key or a model associated with it. You must manually generate the
1139 # join table with a migration such as this:
1140 #
1141 # class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration
1142 # def self.up
1143 # create_table :developers_projects, :id => false do |t|
1144 # t.integer :developer_id
1145 # t.integer :project_id
1146 # end
1147 # end
1148 #
1149 # def self.down
1150 # drop_table :developers_projects
1151 # end
1152 # end
1153 #
53aa8da1 » dhh 2006-04-01 Fixed that records returned... 1154 # Deprecated: Any additional fields added to the join table will be placed as attributes when pulling records out through
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 1155 # +has_and_belongs_to_many+ associations. Records returned from join tables with additional attributes will be marked as
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 1156 # readonly (because we can't save changes to the additional attributes). It's strongly recommended that you upgrade any
53aa8da1 » dhh 2006-04-01 Fixed that records returned... 1157 # associations with attributes to a real join model (see introduction).
db045dbb » dhh 2004-11-23 Initial 1158 #
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 1159 # Adds the following methods for retrieval and query:
6e754551 » lifo 2008-07-28 Merge docrails changes 1160 #
1161 # [collection(force_reload = false)]
1162 # Returns an array of all the associated objects.
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 1163 # An empty array is returned if none are found.
6e754551 » lifo 2008-07-28 Merge docrails changes 1164 # [collection<<(object, ...)]
1165 # Adds one or more objects to the collection by creating associations in the join table
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 1166 # (<tt>collection.push</tt> and <tt>collection.concat</tt> are aliases to this method).
6e754551 » lifo 2008-07-28 Merge docrails changes 1167 # [collection.delete(object, ...)]
1168 # Removes one or more objects from the collection by removing their associations from the join table.
db045dbb » dhh 2004-11-23 Initial 1169 # This does not destroy the objects.
6e754551 » lifo 2008-07-28 Merge docrails changes 1170 # [collection=objects]
1171 # Replaces the collection's content by deleting and adding objects as appropriate.
1172 # [collection_singular_ids]
1173 # Returns an array of the associated objects' ids.
1174 # [collection_singular_ids=ids]
1175 # Replace the collection by the objects identified by the primary keys in +ids+.
1176 # [collection.clear]
1177 # Removes every object from the collection. This does not destroy the objects.
1178 # [collection.empty?]
1179 # Returns +true+ if there are no associated objects.
1180 # [collection.size]
1181 # Returns the number of associated objects.
1182 # [collection.find(id)]
1183 # Finds an associated object responding to the +id+ and that
823554ea » dhh 2005-01-15 Added support for associati... 1184 # meets the condition that it has to be associated with this object.
6e754551 » lifo 2008-07-28 Merge docrails changes 1185 # Uses the same rules as ActiveRecord::Base.find.
c3f53f41 » lifo 2008-12-19 Merge docrails 1186 # [collection.exists?(...)]
6e754551 » lifo 2008-07-28 Merge docrails changes 1187 # Checks whether an associated object with the given conditions exists.
1188 # Uses the same rules as ActiveRecord::Base.exists?.
1189 # [collection.build(attributes = {})]
1190 # Returns a new object of the collection type that has been instantiated
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 1191 # with +attributes+ and linked to this object through the join table, but has not yet been saved.
6e754551 » lifo 2008-07-28 Merge docrails changes 1192 # [collection.create(attributes = {})]
1193 # Returns a new object of the collection type that has been instantiated
18a3333a » NZKoz 2007-08-28 Formatting, grammar and spe... 1194 # with +attributes+, linked to this object through the join table, and that has already been saved (if it passed the validation).
db045dbb » dhh 2004-11-23 Initial 1195 #
6e754551 » lifo 2008-07-28 Merge docrails changes 1196 # (+collection+ is replaced with the symbol passed as the first argument, so
1197 # <tt>has_and_belongs_to_many :categories</tt> would add among others <tt>categories.empty?</tt>.)
1198 #
1199 # === Example
1200 #
1201 # A Developer class declares <tt>has_and_belongs_to_many :projects</tt>, which will add:
db045dbb » dhh 2004-11-23 Initial 1202 # * <tt>Developer#projects</tt>
1203 # * <tt>Developer#projects<<</tt>
1204 # * <tt>Developer#projects.delete</tt>
bfe6a759 » dhh 2005-06-15 Added actual database-chang... 1205 # * <tt>Developer#projects=</tt>
cb0837a2 » dhh 2006-10-08 Doc fixes (closes #6325) 1206 # * <tt>Developer#project_ids</tt>
bfe6a759 » dhh 2005-06-15 Added actual database-chang... 1207 # * <tt>Developer#project_ids=</tt>
db045dbb » dhh 2004-11-23 Initial 1208 # * <tt>Developer#projects.clear</tt>
1209 # * <tt>Developer#projects.empty?</tt>
1210 # * <tt>Developer#projects.size</tt>
1211 # * <tt>Developer#projects.find(id)</tt>
c3f53f41 » lifo 2008-12-19 Merge docrails 1212 # * <tt>Developer#clients.exists?(...)</tt>
06075a9e » technoweenie 2006-05-28 Fix the has_and_belongs_to_... 1213 # * <tt>Developer#projects.build</tt> (similar to <tt>Project.new("project_id" => id)</tt>)
1214 # * <tt>Developer#projects.create</tt> (similar to <tt>c = Project.new("project_id" => id); c.save; c</tt>)
db045dbb » dhh 2004-11-23 Initial 1215 # The declaration may include an options hash to specialize the behavior of the association.
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 1216 #
6e754551 » lifo 2008-07-28 Merge docrails changes 1217 # === Options
1218 #
1219 # [:class_name]
1220 # Specify the class name of the association. Use it only if that name can't be inferred
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 1221 # from the association name. So <tt>has_and_belongs_to_many :projects</tt> will by default be linked to the
dc4eec11 » lifo 2008-05-09 Merge docrails: 1222 # Project class, but if the real class name is SuperProject, you'll have to specify it with this option.
6e754551 » lifo 2008-07-28 Merge docrails changes 1223 # [:join_table]
1224 # Specify the name of the join table if the default based on lexical order isn't what you want.
1225 # <b>WARNING:</b> If you're overwriting the table name of either class, the +table_name+ method
1226 # MUST be declared underneath any +has_and_belongs_to_many+ declaration in order to work.
1227 # [:foreign_key]
1228 # Specify the foreign key used for the association. By default this is guessed to be the name
dc4eec11 » lifo 2008-05-09 Merge docrails: 1229 # of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_and_belongs_to_many+ association
886124e6 » lifo 2009-02-01 Merge docrails 1230 # to Project will use "person_id" as the default <tt>:foreign_key</tt>.
6e754551 » lifo 2008-07-28 Merge docrails changes 1231 # [:association_foreign_key]
886124e6 » lifo 2009-02-01 Merge docrails 1232 # Specify the foreign key used for the association on the receiving side of the association.
1233 # By default this is guessed to be the name of the associated class in lower-case and "_id" suffixed.
1234 # So if a Person class makes a +has_and_belongs_to_many+ association to Project,
1235 # the association will use "project_id" as the default <tt>:association_foreign_key</tt>.
6e754551 » lifo 2008-07-28 Merge docrails changes 1236 # [:conditions]
1237 # Specify the conditions that the associated object must meet in order to be included as a +WHERE+
19d2ff83 » miloops 2009-04-29 Calculations now use Arel t... 1238 # SQL fragment, such as <tt>authorized = 1</tt>. Record creations from the association are scoped if a hash is used.
1239 # <tt>has_many :posts, :conditions => {:published => true}</tt> will create published posts with <tt>@blog.posts.create</tt>
c23c9bd1 » technoweenie 2008-03-21 Allow association scoping f... 1240 # or <tt>@blog.posts.build</tt>.
6e754551 » lifo 2008-07-28 Merge docrails changes 1241 # [:order]
1242 # Specify the order in which the associated objects are returned as an <tt>ORDER BY</tt> SQL fragment,
7143d801 » Marcel Molina 2007-11-07 Smattering of grammatical f... 1243 # such as <tt>last_name, first_name DESC</tt>
6e754551 » lifo 2008-07-28 Merge docrails changes 1244 # [:uniq]
1245 # If true, duplicate associated objects will be ignored by accessors and query methods.
1246 # [:finder_sql]
1247 # Overwrite the default generated SQL statement used to fetch the association with a manual statement
44af2efa » ernie 2008-08-28 Refactored AssociationColle... 1248 # [:counter_sql]
1249 # Specify a complete SQL statement to fetch the size of the association. If <tt>:finder_sql</tt> is
1250 # specified but not <tt>:counter_sql</tt>, <tt>:counter_sql</tt> will be generated by replacing <tt>SELECT ... FROM</tt> with <tt>SELECT COUNT(*) FROM</tt>.
6e754551 » lifo 2008-07-28 Merge docrails changes 1251 # [:delete_sql]
1252 # Overwrite the default generated SQL statement used to remove links between the associated
dc4eec11 » lifo 2008-05-09 Merge docrails: 1253 # classes with a manual statement.
6e754551 » lifo 2008-07-28 Merge docrails changes 1254 # [:insert_sql]
1255 # Overwrite the default generated SQL statement used to add links between the associated classes
dc4eec11 » lifo 2008-05-09 Merge docrails: 1256 # with a manual statement.
6e754551 » lifo 2008-07-28 Merge docrails changes 1257 # [:extend]
1258 # Anonymous module for extending the proxy, see "Association extensions".
1259 # [:include]
1260 # Specify second-order associations that should be eager loaded when the collection is loaded.
1261 # [:group]
1262 # An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
97403ad5 » miloops 2008-11-21 Add :having option to find,... 1263 # [:having]
1264 # Combined with +:group+ this can be used to filter the records that a <tt>GROUP BY</tt> returns. Uses the <tt>HAVING</tt> SQL-clause.
6e754551 » lifo 2008-07-28 Merge docrails changes 1265 # [:limit]
1266 # An integer determining the limit on the number of rows that should be returned.
1267 # [:offset]
1268 # An integer determining the offset from where the rows should be fetched. So at 5, it would skip the first 4 rows.
1269 # [:select]
1270 # By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if, for example, you want to do a join
8d0b4fa3 » josevalim 2008-05-23 Added :select option to has... 1271 # but not include the joined columns. Do not forget to include the primary and foreign keys, otherwise it will raise an error.
6e754551 » lifo 2008-07-28 Merge docrails changes 1272 # [:readonly]
1273 # If true, all the associated objects are readonly through the association.
1274 # [:validate]
1275 # If false, don't validate the associated objects when saving the parent object. +true+ by default.
ec8f0458 » alloy 2009-01-31 Add support for nested obje... Comment 1276 # [:autosave]
1277 # If true, always save any loaded members and destroy members marked for destruction, when saving the parent object. Off by default.
db045dbb » dhh 2004-11-23 Initial 1278 #
1279 # Option examples:
1280 # has_and_belongs_to_many :projects
49c801b7 » dhh 2005-11-06 Added :include as an option... 1281 # has_and_belongs_to_many :projects, :include => [ :milestones, :manager ]
db045dbb » dhh 2004-11-23 Initial 1282 # has_and_belongs_to_many :nations, :class_name => "Country"
1283 # has_and_belongs_to_many :categories, :join_table => "prods_cats"
dfa78663 » jeremy 2008-02-12 Introduce the :readonly opt... 1284 # has_and_belongs_to_many :categories, :readonly => true
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 1285 # has_and_belongs_to_many :active_projects, :join_table => 'developers_projects', :delete_sql =>
190e0464 » dhh 2005-05-19 Fixed that :delete_sql in h... 1286 # 'DELETE FROM developers_projects WHERE active=1 AND developer_id = #{id} AND project_id = #{record.id}'
c8dd66fd » dhh 2005-11-06 Made association extensions... 1287 def has_and_belongs_to_many(association_id, options = {}, &extension)
6abda696 » dhh 2005-12-02 Added preliminary support f... 1288 reflection = create_has_and_belongs_to_many_reflection(association_id, options, &extension)
1289 collection_accessor_methods(reflection, HasAndBelongsToManyAssociation)
db045dbb » dhh 2004-11-23 Initial 1290
35b4bdcf » jeremy 2005-11-08 Destroy associated has_and_... 1291 # Don't use a before_destroy callback since users' before_destroy
1292 # callbacks will be executed after the association is wiped out.
6abda696 » dhh 2005-12-02 Added preliminary support f... 1293 old_method = "destroy_without_habtm_shim_for_#{reflection.name}"
88f951a5 » jeremy 2007-10-27 Allow association redefinit... 1294 class_eval <<-end_eval unless method_defined?(old_method)
a2270ef2 » fxn 2008-12-28 Inline code comments for cl... Comment 1295 alias_method :#{old_method}, :destroy_without_callbacks # alias_method :destroy_without_habtm_shim_for_posts, :destroy_without_callbacks
1296 def destroy_without_callbacks # def destroy_without_callbacks
1297 #{reflection.name}.clear # posts.clear
1298 #{old_method} # destroy_without_habtm_shim_for_posts
1299 end # end
35b4bdcf » jeremy 2005-11-08 Destroy associated has_and_... 1300 end_eval
1301
6abda696 » dhh 2005-12-02 Added preliminary support f... 1302 add_association_callbacks(reflection.name, options)
db045dbb » dhh 2004-11-23 Initial 1303 end
1304
1305 private
6ef35461 » lifo 2008-09-03 Merge docrails 1306 # Generates a join table name from two provided table names.
e033b5d0 » lifo 2009-07-25 Merge docrails 1307 # The names in the join table names end up in lexicographic order.
6ef35461 » lifo 2008-09-03 Merge docrails 1308 #
1309 # join_table_name("members", "clubs") # => "clubs_members"
1310 # join_table_name("members", "special_clubs") # => "members_special_clubs"
db045dbb » dhh 2004-11-23 Initial 1311 def join_table_name(first_table_name, second_table_name)
1312 if first_table_name < second_table_name
1313 join_table = "#{first_table_name}_#{second_table_name}"
1314 else
1315 join_table = "#{second_table_name}_#{first_table_name}"
1316 end
1317
1318 table_name_prefix + join_table + table_name_suffix
1319 end
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 1320
6abda696 » dhh 2005-12-02 Added preliminary support f... 1321 def association_accessor_methods(reflection, association_proxy_class)
1322 define_method(reflection.name) do |*params|
823554ea » dhh 2005-01-15 Added support for associati... 1323 force_reload = params.first unless params.empty?
ec8f0458 » alloy 2009-01-31 Add support for nested obje... Comment 1324 association = association_instance_get(reflection.name)
6abda696 » dhh 2005-12-02 Added preliminary support f... 1325
cb45ee34 » NZKoz 2008-10-10 Remove the functionality in... 1326 if association.nil? || force_reload
6abda696 » dhh 2005-12-02 Added preliminary support f... 1327 association = association_proxy_class.new(self, reflection)
bf6af5f7 » Will 2009-12-16 When passing force_reload =... 1328 retval = force_reload ? reflection.klass.uncached { association.reload } : association.reload
94a13091 » technoweenie 2006-08-08 Cache nil results for has_o... 1329 if retval.nil? and association_proxy_class == BelongsToAssociation
ec8f0458 » alloy 2009-01-31 Add support for nested obje... Comment 1330 association_instance_set(reflection.name, nil)
bce0e149 » dhh 2005-01-18 Fixed that the belongs_to a... 1331 return nil
1332 end
ec8f0458 » alloy 2009-01-31 Add support for nested obje... Comment 1333 association_instance_set(reflection.name, association)
bce0e149 » dhh 2005-01-18 Fixed that the belongs_to a... 1334 end
94a13091 » technoweenie 2006-08-08 Cache nil results for has_o... 1335
1336 association.target.nil? ? nil : association
bce0e149 » dhh 2005-01-18 Fixed that the belongs_to a... 1337 end
1338
4c050554 » willbryant 2008-09-26 explicitly including child ... 1339 define_method("loaded_#{reflection.name}?") do
ec8f0458 » alloy 2009-01-31 Add support for nested obje... Comment 1340 association = association_instance_get(reflection.name)
4c050554 » willbryant 2008-09-26 explicitly including child ... 1341 association && association.loaded?
1342 end
1343
6abda696 » dhh 2005-12-02 Added preliminary support f... 1344 define_method("#{reflection.name}=") do |new_value|
ec8f0458 » alloy 2009-01-31 Add support for nested obje... Comment 1345 association = association_instance_get(reflection.name)
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 1346
4afd6c9f » jeremy 2007-05-21 belongs_to assignment creat... 1347 if association.nil? || association.target != new_value
6abda696 » dhh 2005-12-02 Added preliminary support f... 1348 association = association_proxy_class.new(self, reflection)
bce0e149 » dhh 2005-01-18 Fixed that the belongs_to a... 1349 end
6abda696 » dhh 2005-12-02 Added preliminary support f... 1350
54a54466 » amilligan 2009-05-10 HasOneThroughAssociation st... 1351 association.replace(new_value)
1352 association_instance_set(reflection.name, new_value.nil? ? nil : association)
bce0e149 » dhh 2005-01-18 Fixed that the belongs_to a... 1353 end
f8783abf » dhh 2005-04-03 Made eager loading work eve... 1354
6abda696 » dhh 2005-12-02 Added preliminary support f... 1355 define_method("set_#{reflection.name}_target") do |target|
18057d2f » jeremy 2006-08-17 Cache nil results for :incl... 1356 return if target.nil? and association_proxy_class == BelongsToAssociation
6abda696 » dhh 2005-12-02 Added preliminary support f... 1357 association = association_proxy_class.new(self, reflection)
f8783abf » dhh 2005-04-03 Made eager loading work eve... 1358 association.target = target
ec8f0458 » alloy 2009-01-31 Add support for nested obje... Comment 1359 association_instance_set(reflection.name, association)
f8783abf » dhh 2005-04-03 Made eager loading work eve... 1360 end
bce0e149 » dhh 2005-01-18 Fixed that the belongs_to a... 1361 end
1362
6abda696 » dhh 2005-12-02 Added preliminary support f... 1363 def collection_reader_method(reflection, association_proxy_class)
1364 define_method(reflection.name) do |*params|
bce0e149 » dhh 2005-01-18 Fixed that the belongs_to a... 1365 force_reload = params.first unless params.empty?
ec8f0458 » alloy 2009-01-31 Add support for nested obje... Comment 1366 association = association_instance_get(reflection.name)
6abda696 » dhh 2005-12-02 Added preliminary support f... 1367
ec8f0458 » alloy 2009-01-31 Add support for nested obje... Comment 1368 unless association
6abda696 » dhh 2005-12-02 Added preliminary support f... 1369 association = association_proxy_class.new(self, reflection)
ec8f0458 » alloy 2009-01-31 Add support for nested obje... Comment 1370 association_instance_set(reflection.name, association)
db045dbb » dhh 2004-11-23 Initial 1371 end
6abda696 » dhh 2005-12-02 Added preliminary support f... 1372
bf6af5f7 » Will 2009-12-16 When passing force_reload =... 1373 reflection.klass.uncached { association.reload } if force_reload
6abda696 » dhh 2005-12-02 Added preliminary support f... 1374
823554ea » dhh 2005-01-15 Added support for associati... 1375 association
1376 end
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 1377
1378 define_method("#{reflection.name.to_s.singularize}_ids") do
838cb1aa » jeremy 2008-10-23 Skip collection ids reader ... 1379 if send(reflection.name).loaded? || reflection.options[:finder_sql]
b163d83b » miloops 2008-08-30 Performance: Better query f... 1380 send(reflection.name).map(&:id)
1381 else
373b053d » lifo 2009-07-13 Optimize <association>_ids ... 1382 if reflection.through_reflection && reflection.source_reflection.belongs_to?
1383 through = reflection.through_reflection
1384 primary_key = reflection.source_reflection.primary_key_name
40b38758 » lifo 2009-07-13 Use map! instead of map for... 1385 send(through.name).all(:select => "DISTINCT #{through.quoted_table_name}.#{primary_key}").map!(&:"#{primary_key}")
373b053d » lifo 2009-07-13 Optimize <association>_ids ... 1386 else
40b38758 » lifo 2009-07-13 Use map! instead of map for... 1387 send(reflection.name).all(:select => "#{reflection.quoted_table_name}.#{reflection.klass.primary_key}").map!(&:id)
373b053d » lifo 2009-07-13 Optimize <association>_ids ... 1388 end
b163d83b » miloops 2008-08-30 Performance: Better query f... 1389 end
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 1390 end
373b053d » lifo 2009-07-13 Optimize <association>_ids ... 1391
6abda696 » dhh 2005-12-02 Added preliminary support f... 1392 end
db045dbb » dhh 2004-11-23 Initial 1393
b5b16a80 » jeremy 2007-06-27 Define collection singular ... 1394 def collection_accessor_methods(reflection, association_proxy_class, writer = true)
6abda696 » dhh 2005-12-02 Added preliminary support f... 1395 collection_reader_method(reflection, association_proxy_class)
1396
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 1397 if writer
1398 define_method("#{reflection.name}=") do |new_value|
1399 # Loads proxy class instance (defined in collection_reader_method) if not already loaded
1400 association = send(reflection.name)
1401 association.replace(new_value)
1402 association
1403 end
bfe6a759 » dhh 2005-06-15 Added actual database-chang... 1404
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 1405 define_method("#{reflection.name.to_s.singularize}_ids=") do |new_value|
ea290e77 » dasil003 2009-11-17 Insert generated associatio... 1406 ids = (new_value || []).reject { |nid| nid.blank? }.map(&:to_i)
1407 send("#{reflection.name}=", reflection.klass.find(ids).index_by(&:id).values_at(*ids))
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 1408 end
0092d0ac » jeremy 2006-10-01 Association collections hav... 1409 end
db045dbb » dhh 2004-11-23 Initial 1410 end
ba3ecf53 » clemens 2008-09-02 Some performance goodness f... 1411
6abda696 » dhh 2005-12-02 Added preliminary support f... 1412 def association_constructor_method(constructor, reflection, association_proxy_class)
1413 define_method("#{constructor}_#{reflection.name}") do |*params|
2bdaff4a » dhh 2005-06-06 Added a second parameter to... 1414 attributees = params.first unless params.empty?
1415 replace_existing = params[1].nil? ? true : params[1]
ec8f0458 » alloy 2009-01-31 Add support for nested obje... Comment 1416 association = association_instance_get(reflection.name)
3b9e90a4 » dhh 2005-04-11 Moved build_association and... 1417
ec8f0458 » alloy 2009-01-31 Add support for nested obje... Comment 1418 unless association
6abda696 » dhh 2005-12-02 Added preliminary support f... 1419 association = association_proxy_class.new(self, reflection)
ec8f0458 » alloy 2009-01-31 Add support for nested obje... Comment 1420 association_instance_set(reflection.name, association)
3b9e90a4 » dhh 2005-04-11 Moved build_association and... 1421 end
1422
bfe6a759 » dhh 2005-06-15 Added actual database-chang... 1423 if association_proxy_class == HasOneAssociation
1424 association.send(constructor, attributees, replace_existing)
1425 else
1426 association.send(constructor, attributees)
1427 end
3b9e90a4 » dhh 2005-04-11 Moved build_association and... 1428 end
1429 end
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 1430
abb899c5 » dhh 2009-04-16 Added :touch option to belo... Comment 1431 def add_counter_cache_callbacks(reflection)
1432 cache_column = reflection.counter_cache_column
1433
1434 method_name = "belongs_to_counter_cache_after_create_for_#{reflection.name}".to_sym
1435 define_method(method_name) do
1436 association = send(reflection.name)
1c11437a » szimek 2009-07-15 Add primary_key option to b... Comment 1437 association.class.increment_counter(cache_column, association.id) unless association.nil?
abb899c5 » dhh 2009-04-16 Added :touch option to belo... Comment 1438 end
1439 after_create(method_name)
1440
1441 method_name = "belongs_to_counter_cache_before_destroy_for_#{reflection.name}".to_sym
1442 define_method(method_name) do
1443 association = send(reflection.name)
1c11437a » szimek 2009-07-15 Add primary_key option to b... Comment 1444 association.class.decrement_counter(cache_column, association.id) unless association.nil?
abb899c5 » dhh 2009-04-16 Added :touch option to belo... Comment 1445 end
1446 before_destroy(method_name)
1447
1448 module_eval(
1449 "#{reflection.class_name}.send(:attr_readonly,\"#{cache_column}\".intern) if defined?(#{reflection.class_name}) && #{reflection.class_name}.respond_to?(:attr_readonly)"
1450 )
1451 end
19d2ff83 » miloops 2009-04-29 Calculations now use Arel t... 1452
abb899c5 » dhh 2009-04-16 Added :touch option to belo... Comment 1453 def add_touch_callbacks(reflection, touch_attribute)
1454 method_name = "belongs_to_touch_after_save_or_destroy_for_#{reflection.name}".to_sym
1455 define_method(method_name) do
1456 association = send(reflection.name)
19d2ff83 » miloops 2009-04-29 Calculations now use Arel t... 1457
abb899c5 » dhh 2009-04-16 Added :touch option to belo... Comment 1458 if touch_attribute == true
1459 association.touch unless association.nil?
1460 else
1461 association.touch(touch_attribute) unless association.nil?
1462 end
1463 end
1464 after_save(method_name)
1465 after_destroy(method_name)
1466 end
1467
65f055a3 » miloops 2009-10-05 Added eager loading support... 1468 def find_with_associations(options = {}, join_dependency = nil)
31d8169e » technoweenie 2006-04-05 Fixed that loading includin... 1469 catch :invalid_query do
65f055a3 » miloops 2009-10-05 Added eager loading support... 1470 join_dependency ||= JoinDependency.new(self, merge_includes(scope(:find, :include), options[:include]), options[:joins])
31d8169e » technoweenie 2006-04-05 Fixed that loading includin... 1471 rows = select_all_rows(options, join_dependency)
1472 return join_dependency.instantiate(rows)
1473 end
1474 []
3a7be80f » dhh 2006-03-15 Change LEFT OUTER JOIN auth... 1475 end
6f344000 » dhh 2005-04-19 Fixed order of loading in e... 1476
72b772ae » Hongli Lai (Phusion) 2008-09-21 Refactor configure_dependen... 1477 # Creates before_destroy callback methods that nullify, delete or destroy
1478 # has_many associated objects, according to the defined :dependent rule.
1479 #
aa04635d » jeremy 2007-10-08 Update :dependent docs and ... 1480 # See HasManyAssociation#delete_records. Dependent associations
1481 # delete children, otherwise foreign key is set to NULL.
72b772ae » Hongli Lai (Phusion) 2008-09-21 Refactor configure_dependen... 1482 #
1483 # The +extra_conditions+ parameter, which is not used within the main
1484 # Active Record codebase, is meant to allow plugins to define extra
1485 # finder conditions.
1486 def configure_dependency_for_has_many(reflection, extra_conditions = nil)
aa04635d » jeremy 2007-10-08 Update :dependent docs and ... 1487 if reflection.options.include?(:dependent)
1488 # Add polymorphic type if the :as option is present
1489 dependent_conditions = []
d625312f » al2o3cr 2009-11-07 delete correct records for ... 1490 dependent_conditions << "#{reflection.primary_key_name} = \#{record.#{reflection.name}.send(:owner_quoted_id)}"
aa04635d » jeremy 2007-10-08 Update :dependent docs and ... 1491 dependent_conditions << "#{reflection.options[:as]}_type = '#{base_class.name}'" if reflection.options[:as]
de0ea386 » lifo 2009-04-20 Ensure :dependent => :delet... 1492 dependent_conditions << sanitize_sql(reflection.options[:conditions], reflection.quoted_table_name) if reflection.options[:conditions]
72b772ae » Hongli Lai (Phusion) 2008-09-21 Refactor configure_dependen... 1493 dependent_conditions << extra_conditions if extra_conditions
aa04635d » jeremy 2007-10-08 Update :dependent docs and ... 1494 dependent_conditions = dependent_conditions.collect {|where| "(#{where})" }.join(" AND ")
b17b9371 » fcheung 2008-12-21 Fix configure_dependency_fo... 1495 dependent_conditions = dependent_conditions.gsub('@', '\@')
aa04635d » jeremy 2007-10-08 Update :dependent docs and ... 1496 case reflection.options[:dependent]
1497 when :destroy
de048b10 » technoweenie 2008-02-13 Improve associations perfor... 1498 method_name = "has_many_dependent_destroy_for_#{reflection.name}".to_sym
1499 define_method(method_name) do
ba3ecf53 » clemens 2008-09-02 Some performance goodness f... 1500 send(reflection.name).each { |o| o.destroy }
de048b10 » technoweenie 2008-02-13 Improve associations perfor... 1501 end
1502 before_destroy method_name
aa04635d » jeremy 2007-10-08 Update :dependent docs and ... 1503 when :delete_all
4f37b970 » josevalim 2009-09-08 Changed ActiveRecord to use... 1504 # before_destroy do |record|
1505 # self.class.send(:delete_all_has_many_dependencies,
1506 # record,
1507 # "posts",
1508 # Post,
1509 # %@...@) # this is a string literal like %(...)
1510 # end
1511 # end
1512 module_eval <<-CALLBACK
1513 before_destroy do |record|
1514 self.class.send(:delete_all_has_many_dependencies,
1515 record,
1516 "#{reflection.name}",
1517 #{reflection.class_name},
1518 %@#{dependent_conditions}@)
1519 end
1520 CALLBACK
aa04635d » jeremy 2007-10-08 Update :dependent docs and ... 1521 when :nullify
4f37b970 » josevalim 2009-09-08 Changed ActiveRecord to use... 1522 # before_destroy do |record|
1523 # self.class.send(:nullify_has_many_dependencies,
1524 # record,
1525 # "posts",
1526 # Post,
1527 # "user_id",
1528 # %@...@) # this is a string literal like %(...)
1529 # end
1530 # end
1531 module_eval <<-CALLBACK
1532 before_destroy do |record|
1533 self.class.send(:nullify_has_many_dependencies,
1534 record,
1535 "#{reflection.name}",
1536 #{reflection.class_name},
1537 "#{reflection.primary_key_name}",
1538 %@#{dependent_conditions}@)
1539 end
1540 CALLBACK
aa04635d » jeremy 2007-10-08 Update :dependent docs and ... 1541 else
1542 raise ArgumentError, "The :dependent option expects either :destroy, :delete_all, or :nullify (#{reflection.options[:dependent].inspect})"
1543 end
6abda696 » dhh 2005-12-02 Added preliminary support f... 1544 end
1545 end
3f1acf49 » jeremy 2006-09-15 Deprecation tests. Remove w... 1546
a2932784 » lifo 2008-10-05 Merge docrails 1547 # Creates before_destroy callback methods that nullify, delete or destroy
1548 # has_one associated objects, according to the defined :dependent rule.
6abda696 » dhh 2005-12-02 Added preliminary support f... 1549 def configure_dependency_for_has_one(reflection)
aa04635d » jeremy 2007-10-08 Update :dependent docs and ... 1550 if reflection.options.include?(:dependent)
1551 case reflection.options[:dependent]
1552 when :destroy
de048b10 » technoweenie 2008-02-13 Improve associations perfor... 1553 method_name = "has_one_dependent_destroy_for_#{reflection.name}".to_sym
1554 define_method(method_name) do
ba3ecf53 » clemens 2008-09-02 Some performance goodness f... 1555 association = send(reflection.name)
de048b10 » technoweenie 2008-02-13 Improve associations perfor... 1556 association.destroy unless association.nil?
1557 end
1558 before_destroy method_name
aa04635d » jeremy 2007-10-08 Update :dependent docs and ... 1559 when :delete
de048b10 » technoweenie 2008-02-13 Improve associations perfor... 1560 method_name = "has_one_dependent_delete_for_#{reflection.name}".to_sym
1561 define_method(method_name) do
a2932784 » lifo 2008-10-05 Merge docrails 1562 # Retrieve the associated object and delete it. The retrieval
1563 # is necessary because there may be multiple associated objects
1564 # with foreign keys pointing to this object, and we only want
1565 # to delete the correct one, not all of them.
ba3ecf53 » clemens 2008-09-02 Some performance goodness f... 1566 association = send(reflection.name)
46939a9b » Hongli Lai (Phusion 2008-09-21 Add Model#delete instance m... Comment 1567 association.delete unless association.nil?
de048b10 » technoweenie 2008-02-13 Improve associations perfor... 1568 end
1569 before_destroy method_name
aa04635d » jeremy 2007-10-08 Update :dependent docs and ... 1570 when :nullify
de048b10 » technoweenie 2008-02-13 Improve associations perfor... 1571 method_name = "has_one_dependent_nullify_for_#{reflection.name}".to_sym
1572 define_method(method_name) do
ba3ecf53 » clemens 2008-09-02 Some performance goodness f... 1573 association = send(reflection.name)
1574 association.update_attribute(reflection.primary_key_name, nil) unless association.nil?
de048b10 » technoweenie 2008-02-13 Improve associations perfor... 1575 end
1576 before_destroy method_name
aa04635d » jeremy 2007-10-08 Update :dependent docs and ... 1577 else
1578 raise ArgumentError, "The :dependent option expects either :destroy, :delete or :nullify (#{reflection.options[:dependent].inspect})"
1579 end
6abda696 » dhh 2005-12-02 Added preliminary support f... 1580 end
1581 end
1582
16b129a6 » jeremy 2008-01-18 belongs_to supports :depend... 1583 def configure_dependency_for_belongs_to(reflection)
1584 if reflection.options.include?(:dependent)
1585 case reflection.options[:dependent]
1586 when :destroy
de048b10 » technoweenie 2008-02-13 Improve associations perfor... 1587 method_name = "belongs_to_dependent_destroy_for_#{reflection.name}".to_sym
1588 define_method(method_name) do
ba3ecf53 » clemens 2008-09-02 Some performance goodness f... 1589 association = send(reflection.name)
de048b10 » technoweenie 2008-02-13 Improve associations perfor... 1590 association.destroy unless association.nil?
1591 end
0e92f670 » bvandenbos 2009-01-05 Make belongs_to :dependent ... 1592 after_destroy method_name
16b129a6 » jeremy 2008-01-18 belongs_to supports :depend... 1593 when :delete
de048b10 » technoweenie 2008-02-13 Improve associations perfor... 1594 method_name = "belongs_to_dependent_delete_for_#{reflection.name}".to_sym
1595 define_method(method_name) do
ba3ecf53 » clemens 2008-09-02 Some performance goodness f... 1596 association = send(reflection.name)
46939a9b » Hongli Lai (Phusion 2008-09-21 Add Model#delete instance m... Comment 1597 association.delete unless association.nil?
de048b10 » technoweenie 2008-02-13 Improve associations perfor... 1598 end
0e92f670 » bvandenbos 2009-01-05 Make belongs_to :dependent ... 1599 after_destroy method_name
16b129a6 » jeremy 2008-01-18 belongs_to supports :depend... 1600 else
1601 raise ArgumentError, "The :dependent option expects either :destroy or :delete (#{reflection.options[:dependent].inspect})"
1602 end
1603 end
1604 end
1605
72b772ae » Hongli Lai (Phusion) 2008-09-21 Refactor configure_dependen... 1606 def delete_all_has_many_dependencies(record, reflection_name, association_class, dependent_conditions)
1607 association_class.delete_all(dependent_conditions)
1608 end
1609
1610 def nullify_has_many_dependencies(record, reflection_name, association_class, primary_key_name, dependent_conditions)
1611 association_class.update_all("#{primary_key_name} = NULL", dependent_conditions)
1612 end
1613
16929404 » Hongli Lai (Phusion) 2008-09-06 Make the options that has_m... 1614 mattr_accessor :valid_keys_for_has_many_association
1615 @@valid_keys_for_has_many_association = [
1616 :class_name, :table_name, :foreign_key, :primary_key,
1617 :dependent,
97403ad5 » miloops 2008-11-21 Add :having option to find,... 1618 :select, :conditions, :include, :order, :group, :having, :limit, :offset,
16929404 » Hongli Lai (Phusion) 2008-09-06 Make the options that has_m... 1619 :as, :through, :source, :source_type,
1620 :uniq,
1621 :finder_sql, :counter_sql,
1622 :before_add, :after_add, :before_remove, :after_remove,
1623 :extend, :readonly,
ccea9838 » h-lame 2009-05-01 Providing support for :inve... Comment 1624 :validate, :inverse_of
16929404 » Hongli Lai (Phusion) 2008-09-06 Make the options that has_m... 1625 ]
1626
6abda696 » dhh 2005-12-02 Added preliminary support f... 1627 def create_has_many_reflection(association_id, options, &extension)
16929404 » Hongli Lai (Phusion) 2008-09-06 Make the options that has_m... 1628 options.assert_valid_keys(valid_keys_for_has_many_association)
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 1629 options[:extend] = create_extension_modules(association_id, extension, options[:extend])
6abda696 » dhh 2005-12-02 Added preliminary support f... 1630
8203a2af » dhh 2006-02-26 Dont require association cl... 1631 create_reflection(:has_many, association_id, options, self)
6abda696 » dhh 2005-12-02 Added preliminary support f... 1632 end
1633
16929404 » Hongli Lai (Phusion) 2008-09-06 Make the options that has_m... 1634 mattr_accessor :valid_keys_for_has_one_association
1635 @@valid_keys_for_has_one_association = [
1636 :class_name, :foreign_key, :remote, :select, :conditions, :order,
1637 :include, :dependent, :counter_cache, :extend, :as, :readonly,
ccea9838 » h-lame 2009-05-01 Providing support for :inve... Comment 1638 :validate, :primary_key, :inverse_of
16929404 » Hongli Lai (Phusion) 2008-09-06 Make the options that has_m... 1639 ]
1640
6abda696 » dhh 2005-12-02 Added preliminary support f... 1641 def create_has_one_reflection(association_id, options)
16929404 » Hongli Lai (Phusion) 2008-09-06 Make the options that has_m... 1642 options.assert_valid_keys(valid_keys_for_has_one_association)
8203a2af » dhh 2006-02-26 Dont require association cl... 1643 create_reflection(:has_one, association_id, options, self)
6abda696 » dhh 2005-12-02 Added preliminary support f... 1644 end
ba3ecf53 » clemens 2008-09-02 Some performance goodness f... 1645
273b21fa » technoweenie 2008-03-21 Add has_one :through suppor... 1646 def create_has_one_through_reflection(association_id, options)
1647 options.assert_valid_keys(
7f140bbd » DefV 2008-06-11 Add :validate option to ass... 1648 :class_name, :foreign_key, :remote, :select, :conditions, :order, :include, :dependent, :counter_cache, :extend, :as, :through, :source, :source_type, :validate
273b21fa » technoweenie 2008-03-21 Add has_one :through suppor... 1649 )
1650 create_reflection(:has_one, association_id, options, self)
1651 end
6abda696 » dhh 2005-12-02 Added preliminary support f... 1652
16929404 » Hongli Lai (Phusion) 2008-09-06 Make the options that has_m... 1653 mattr_accessor :valid_keys_for_belongs_to_association
1654 @@valid_keys_for_belongs_to_association = [
1c11437a » szimek 2009-07-15 Add primary_key option to b... Comment 1655 :class_name, :primary_key, :foreign_key, :foreign_type, :remote, :select, :conditions,
16929404 » Hongli Lai (Phusion) 2008-09-06 Make the options that has_m... 1656 :include, :dependent, :counter_cache, :extend, :polymorphic, :readonly,
ccea9838 » h-lame 2009-05-01 Providing support for :inve... Comment 1657 :validate, :touch, :inverse_of
16929404 » Hongli Lai (Phusion) 2008-09-06 Make the options that has_m... 1658 ]
1659
6abda696 » dhh 2005-12-02 Added preliminary support f... 1660 def create_belongs_to_reflection(association_id, options)
16929404 » Hongli Lai (Phusion) 2008-09-06 Make the options that has_m... 1661 options.assert_valid_keys(valid_keys_for_belongs_to_association)
6abda696 » dhh 2005-12-02 Added preliminary support f... 1662 reflection = create_reflection(:belongs_to, association_id, options, self)
1663
1664 if options[:polymorphic]
1665 reflection.options[:foreign_type] ||= reflection.class_name.underscore + "_type"
1666 end
1667
1668 reflection
1669 end
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 1670
5229fc4c » jodosha 2008-10-31 Make sure habtm use class v... 1671 mattr_accessor :valid_keys_for_has_and_belongs_to_many_association
1672 @@valid_keys_for_has_and_belongs_to_many_association = [
1673 :class_name, :table_name, :join_table, :foreign_key, :association_foreign_key,
97403ad5 » miloops 2008-11-21 Add :having option to find,... 1674 :select, :conditions, :include, :order, :group, :having, :limit, :offset,
5229fc4c » jodosha 2008-10-31 Make sure habtm use class v... 1675 :uniq,
26978e3c » tekin 2008-11-06 Added :counter_sql as a val... 1676 :finder_sql, :counter_sql, :delete_sql, :insert_sql,
5229fc4c » jodosha 2008-10-31 Make sure habtm use class v... 1677 :before_add, :after_add, :before_remove, :after_remove,
1678 :extend, :readonly,
1679 :validate
1680 ]
1681
6abda696 » dhh 2005-12-02 Added preliminary support f... 1682 def create_has_and_belongs_to_many_reflection(association_id, options, &extension)
5229fc4c » jodosha 2008-10-31 Make sure habtm use class v... 1683 options.assert_valid_keys(valid_keys_for_has_and_belongs_to_many_association)
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 1684 options[:extend] = create_extension_modules(association_id, extension, options[:extend])
6abda696 » dhh 2005-12-02 Added preliminary support f... 1685
1686 reflection = create_reflection(:has_and_belongs_to_many, association_id, options, self)
19d2ff83 » miloops 2009-04-29 Calculations now use Arel t... 1687
c896d56c » cwninja 2009-03-06 Ensure self referential HAB... 1688 if reflection.association_foreign_key == reflection.primary_key_name
1689 raise HasAndBelongsToManyAssociationForeignKeyNeeded.new(reflection)
1690 end
6abda696 » dhh 2005-12-02 Added preliminary support f... 1691
3b6a9a02 » jeremy 2009-09-02 Revert "Assert primary key ... 1692 reflection.options[:join_table] ||= join_table_name(undecorated_table_name(self.to_s), undecorated_table_name(reflection.class_name))
78790e47 » jeremy 2009-11-23 Revert "Revert "Assert prim... 1693 if connection.supports_primary_key? && (connection.primary_key(reflection.options[:join_table]) rescue false)
1694 raise HasAndBelongsToManyAssociationWithPrimaryKeyError.new(reflection)
1695 end
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 1696
6abda696 » dhh 2005-12-02 Added preliminary support f... 1697 reflection
1698 end
1699
55854c41 » dhh 2006-03-04 Added cascading eager loadi... 1700 def select_all_rows(options, join_dependency)
49d0f0cb » dhh 2005-04-18 Speeded up eager loading a ... 1701 connection.select_all(
55854c41 » dhh 2006-03-04 Added cascading eager loadi... 1702 construct_finder_sql_with_included_associations(options, join_dependency),
49d0f0cb » dhh 2005-04-18 Speeded up eager loading a ... 1703 "#{name} Load Including Associations"
1704 )
1705 end
057cf491 » dhh 2005-04-10 Added support for has_and_b... 1706
9ac01fad » miloops 2009-08-14 Use ARel's joins when build... 1707 def construct_finder_arel_with_included_associations(options, join_dependency)
c9c18520 » dhh 2006-03-27 Making ActiveRecord faster ... 1708 scope = scope(:find)
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 1709
7b3d85db » jeremy 2009-11-13 Revert "Split arel_table in... 1710 relation = arel_table((scope && scope[:from]) || options[:from])
945ef585 » miloops 2009-08-07 More work on removing plain... 1711
9ac01fad » miloops 2009-08-14 Use ARel's joins when build... 1712 for association in join_dependency.join_associations
c9234096 » miloops 2009-08-17 Clean up relation joins whe... 1713 relation = association.join_relation(relation)
9ac01fad » miloops 2009-08-14 Use ARel's joins when build... 1714 end
851dd080 » dhh 2005-10-18 Added support for using lim... 1715
66fbcc1d » miloops 2009-08-18 Use immutable relation obje... 1716 relation = relation.joins(construct_join(options[:joins], scope)).
1717 select(column_aliases(join_dependency)).
1718 group(construct_group(options[:group], options[:having], scope)).
1719 order(construct_order(options[:order], scope)).
1720 conditions(construct_conditions(options[:conditions], scope))
8c3b8323 » miloops 2009-06-10 Use ARel in SQL generation ... 1721
66fbcc1d » miloops 2009-08-18 Use immutable relation obje... 1722 relation = relation.conditions(construct_arel_limited_ids_condition(options, join_dependency)) if !using_limitable_reflections?(join_dependency.reflections) && ((scope && scope[:limit]) || options[:limit])
1723 relation = relation.limit(construct_limit(options[:limit], scope)) if using_limitable_reflections?(join_dependency.reflections)
8c3b8323 » miloops 2009-06-10 Use ARel in SQL generation ... 1724
9ac01fad » miloops 2009-08-14 Use ARel's joins when build... 1725 relation
1726 end
1727
1728 def construct_finder_sql_with_included_associations(options, join_dependency)
b3247402 » miloops 2009-08-19 Don't sanitize_sql where it... 1729 construct_finder_arel_with_included_associations(options, join_dependency).to_sql
abc895b8 » dhh 2005-04-03 Added new Base.find API and... 1730 end
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 1731
945ef585 » miloops 2009-08-07 More work on removing plain... 1732 def construct_arel_limited_ids_condition(options, join_dependency)
1733 if (ids_array = select_limited_ids_array(options, join_dependency)).empty?
19d2ff83 » miloops 2009-04-29 Calculations now use Arel t... 1734 throw :invalid_query
945ef585 » miloops 2009-08-07 More work on removing plain... 1735 else
e93c2da1 » jeremy 2009-11-02 Arel::In -> Arel::Predicate... 1736 Arel::Predicates::In.new(
945ef585 » miloops 2009-08-07 More work on removing plain... 1737 Arel::SqlLiteral.new("#{connection.quote_table_name table_name}.#{primary_key}"),
1738 ids_array
1739 )
19d2ff83 » miloops 2009-04-29 Calculations now use Arel t... 1740 end
1741 end
1742
945ef585 » miloops 2009-08-07 More work on removing plain... 1743 def select_limited_ids_array(options, join_dependency)
5ea76fab » technoweenie 2006-04-18 Associations#select_limited... 1744 connection.select_all(
55854c41 » dhh 2006-03-04 Added cascading eager loadi... 1745 construct_finder_sql_for_association_limiting(options, join_dependency),
851dd080 » dhh 2005-10-18 Added support for using lim... 1746 "#{name} Load IDs For Limited Eager Loading"
945ef585 » miloops 2009-08-07 More work on removing plain... 1747 ).collect { |row| row[primary_key] }
851dd080 » dhh 2005-10-18 Added support for using lim... 1748 end
c0bce43e » jeremy 2006-11-10 Oracle: fix limited id sele... 1749
55854c41 » dhh 2006-03-04 Added cascading eager loadi... 1750 def construct_finder_sql_for_association_limiting(options, join_dependency)
0e2fbd80 » miloops 2009-08-10 Merge commit 'rails/master' 1751 scope = scope(:find)
8c91b767 » tarmo 2008-07-14 Fixed postgresql limited ea... 1752
7b3d85db » jeremy 2009-11-13 Revert "Split arel_table in... 1753 relation = arel_table(options[:from])
c0bce43e » jeremy 2006-11-10 Oracle: fix limited id sele... 1754
9ac01fad » miloops 2009-08-14 Use ARel's joins when build... 1755 for association in join_dependency.join_associations
c9234096 » miloops 2009-08-17 Clean up relation joins whe... 1756 relation = association.join_relation(relation)
9ac01fad » miloops 2009-08-14 Use ARel's joins when build... 1757 end
c0bce43e » jeremy 2006-11-10 Oracle: fix limited id sele... 1758
66fbcc1d » miloops 2009-08-18 Use immutable relation obje... 1759 relation = relation.joins(construct_join(options[:joins], scope)).
1760 conditions(construct_conditions(options[:conditions], scope)).
1761 group(construct_group(options[:group], options[:having], scope)).
1762 order(construct_order(options[:order], scope)).
1763 limit(construct_limit(options[:limit], scope)).
1764 offset(construct_limit(options[:offset], scope)).
1765 select(connection.distinct("#{connection.quote_table_name table_name}.#{primary_key}", construct_order(options[:order], scope(:find)).join(",")))
0e452bb0 » dhh 2007-08-21 Fixed that eager loading qu... 1766
b3247402 » miloops 2009-08-19 Don't sanitize_sql where it... 1767 relation.to_sql
851dd080 » dhh 2005-10-18 Added support for using lim... 1768 end
c98b471c » technoweenie 2006-10-08 Reverted old select_limited... 1769
c9ab7098 » fcheung 2008-12-18 Ensure :include checks join... 1770 def tables_in_string(string)
1771 return [] if string.blank?
27de7f15 » floering 2009-05-17 Fixed limited eager loading... 1772 string.scan(/([a-zA-Z_][\.\w]+).?\./).flatten
c9ab7098 » fcheung 2008-12-18 Ensure :include checks join... 1773 end
1774
026b78f9 » anthonycrumley 2009-05-04 Fixed eager load error on f... Comment 1775 def tables_in_hash(hash)
1776 return [] if hash.blank?
1777