bigrecord 0.0.5

Sign up to get free protection for your applications and to get access to all the features.
Files changed (104) hide show
  1. data/MIT-LICENSE +20 -0
  2. data/README.rdoc +44 -0
  3. data/Rakefile +17 -0
  4. data/VERSION +1 -0
  5. data/doc/bigrecord_specs.rdoc +36 -0
  6. data/doc/getting_started.rdoc +157 -0
  7. data/examples/bigrecord.yml +25 -0
  8. data/generators/bigrecord/bigrecord_generator.rb +17 -0
  9. data/generators/bigrecord/templates/bigrecord.rake +47 -0
  10. data/generators/bigrecord_migration/bigrecord_migration_generator.rb +13 -0
  11. data/generators/bigrecord_migration/templates/migration.rb +9 -0
  12. data/generators/bigrecord_model/bigrecord_model_generator.rb +28 -0
  13. data/generators/bigrecord_model/templates/migration.rb +13 -0
  14. data/generators/bigrecord_model/templates/model.rb +7 -0
  15. data/generators/bigrecord_model/templates/model_spec.rb +12 -0
  16. data/init.rb +9 -0
  17. data/install.rb +22 -0
  18. data/lib/big_record/abstract_base.rb +1088 -0
  19. data/lib/big_record/action_view_extensions.rb +266 -0
  20. data/lib/big_record/ar_associations/association_collection.rb +194 -0
  21. data/lib/big_record/ar_associations/association_proxy.rb +158 -0
  22. data/lib/big_record/ar_associations/belongs_to_association.rb +57 -0
  23. data/lib/big_record/ar_associations/belongs_to_many_association.rb +57 -0
  24. data/lib/big_record/ar_associations/has_and_belongs_to_many_association.rb +164 -0
  25. data/lib/big_record/ar_associations/has_many_association.rb +191 -0
  26. data/lib/big_record/ar_associations/has_one_association.rb +80 -0
  27. data/lib/big_record/ar_associations.rb +1608 -0
  28. data/lib/big_record/ar_reflection.rb +223 -0
  29. data/lib/big_record/attribute_methods.rb +75 -0
  30. data/lib/big_record/base.rb +618 -0
  31. data/lib/big_record/br_associations/association_collection.rb +194 -0
  32. data/lib/big_record/br_associations/association_proxy.rb +153 -0
  33. data/lib/big_record/br_associations/belongs_to_association.rb +52 -0
  34. data/lib/big_record/br_associations/belongs_to_many_association.rb +293 -0
  35. data/lib/big_record/br_associations/cached_item_proxy.rb +194 -0
  36. data/lib/big_record/br_associations/cached_item_proxy_factory.rb +62 -0
  37. data/lib/big_record/br_associations/has_and_belongs_to_many_association.rb +168 -0
  38. data/lib/big_record/br_associations/has_one_association.rb +80 -0
  39. data/lib/big_record/br_associations.rb +978 -0
  40. data/lib/big_record/br_reflection.rb +151 -0
  41. data/lib/big_record/callbacks.rb +367 -0
  42. data/lib/big_record/connection_adapters/abstract/connection_specification.rb +279 -0
  43. data/lib/big_record/connection_adapters/abstract/database_statements.rb +175 -0
  44. data/lib/big_record/connection_adapters/abstract/quoting.rb +58 -0
  45. data/lib/big_record/connection_adapters/abstract_adapter.rb +190 -0
  46. data/lib/big_record/connection_adapters/column.rb +491 -0
  47. data/lib/big_record/connection_adapters/hbase_adapter.rb +432 -0
  48. data/lib/big_record/connection_adapters/view.rb +27 -0
  49. data/lib/big_record/connection_adapters.rb +10 -0
  50. data/lib/big_record/deletion.rb +73 -0
  51. data/lib/big_record/dynamic_schema.rb +92 -0
  52. data/lib/big_record/embedded.rb +71 -0
  53. data/lib/big_record/embedded_associations/association_proxy.rb +148 -0
  54. data/lib/big_record/family_span_columns.rb +89 -0
  55. data/lib/big_record/fixtures.rb +1025 -0
  56. data/lib/big_record/migration.rb +380 -0
  57. data/lib/big_record/routing_ext.rb +65 -0
  58. data/lib/big_record/timestamp.rb +51 -0
  59. data/lib/big_record/validations.rb +830 -0
  60. data/lib/big_record.rb +125 -0
  61. data/lib/bigrecord.rb +1 -0
  62. data/rails/init.rb +9 -0
  63. data/spec/connections/bigrecord.yml +13 -0
  64. data/spec/connections/cassandra/connection.rb +2 -0
  65. data/spec/connections/hbase/connection.rb +2 -0
  66. data/spec/debug.log +281 -0
  67. data/spec/integration/br_associations_spec.rb +80 -0
  68. data/spec/lib/animal.rb +12 -0
  69. data/spec/lib/book.rb +10 -0
  70. data/spec/lib/broken_migrations/duplicate_name/20090706182535_add_animals_table.rb +14 -0
  71. data/spec/lib/broken_migrations/duplicate_name/20090706193019_add_animals_table.rb +9 -0
  72. data/spec/lib/broken_migrations/duplicate_version/20090706190623_add_books_table.rb +9 -0
  73. data/spec/lib/broken_migrations/duplicate_version/20090706190623_add_companies_table.rb +9 -0
  74. data/spec/lib/company.rb +14 -0
  75. data/spec/lib/embedded/web_link.rb +12 -0
  76. data/spec/lib/employee.rb +33 -0
  77. data/spec/lib/migrations/20090706182535_add_animals_table.rb +13 -0
  78. data/spec/lib/migrations/20090706190623_add_books_table.rb +15 -0
  79. data/spec/lib/migrations/20090706193019_add_companies_table.rb +14 -0
  80. data/spec/lib/migrations/20090706194512_add_employees_table.rb +13 -0
  81. data/spec/lib/migrations/20090706195741_add_zoos_table.rb +13 -0
  82. data/spec/lib/novel.rb +5 -0
  83. data/spec/lib/zoo.rb +17 -0
  84. data/spec/spec.opts +4 -0
  85. data/spec/spec_helper.rb +55 -0
  86. data/spec/unit/abstract_base_spec.rb +287 -0
  87. data/spec/unit/adapters/abstract_adapter_spec.rb +56 -0
  88. data/spec/unit/adapters/adapter_shared_spec.rb +51 -0
  89. data/spec/unit/adapters/hbase_adapter_spec.rb +15 -0
  90. data/spec/unit/ar_associations_spec.rb +8 -0
  91. data/spec/unit/base_spec.rb +6 -0
  92. data/spec/unit/br_associations_spec.rb +58 -0
  93. data/spec/unit/embedded_spec.rb +43 -0
  94. data/spec/unit/find_spec.rb +34 -0
  95. data/spec/unit/hash_helper_spec.rb +44 -0
  96. data/spec/unit/migration_spec.rb +144 -0
  97. data/spec/unit/model_spec.rb +315 -0
  98. data/spec/unit/validations_spec.rb +182 -0
  99. data/tasks/bigrecord_tasks.rake +47 -0
  100. data/tasks/data_store.rb +46 -0
  101. data/tasks/gem.rb +22 -0
  102. data/tasks/rdoc.rb +8 -0
  103. data/tasks/spec.rb +34 -0
  104. metadata +189 -0
@@ -0,0 +1,978 @@
1
+ require 'big_record/br_associations/association_proxy'
2
+ require 'big_record/br_associations/association_collection'
3
+ require 'big_record/br_associations/belongs_to_association'
4
+ require 'big_record/br_associations/belongs_to_many_association'
5
+ require 'big_record/br_associations/has_one_association'
6
+ require 'big_record/br_associations/has_and_belongs_to_many_association'
7
+
8
+ module BigRecord
9
+ module BrAssociations # :nodoc:
10
+ def self.included(base)
11
+ base.extend(ClassMethods)
12
+ end
13
+
14
+ # Associations are a set of macro-like class methods for tying objects together through foreign keys. They express relationships like
15
+ # "Project has one Project Manager" or "Project belongs to a Portfolio". Each macro adds a number of methods to the class which are
16
+ # specialized according to the collection or association symbol and the options hash. It works much the same way as Ruby's own attr*
17
+ # methods. Example:
18
+ #
19
+ # class Project < BigRecord::Base
20
+ # belongs_to :portfolio
21
+ # has_one :project_manager
22
+ # has_many :milestones
23
+ # has_and_belongs_to_many :categories
24
+ # end
25
+ #
26
+ # The project class now has the following methods (and more) to ease the traversal and manipulation of its relationships:
27
+ # * <tt>Project#portfolio, Project#portfolio=(portfolio), Project#portfolio.nil?</tt>
28
+ # * <tt>Project#project_manager, Project#project_manager=(project_manager), Project#project_manager.nil?,</tt>
29
+ # * <tt>Project#milestones.empty?, Project#milestones.size, Project#milestones, Project#milestones<<(milestone),</tt>
30
+ # <tt>Project#milestones.delete(milestone), Project#milestones.find(milestone_id), Project#milestones.find(:all, options),</tt>
31
+ # <tt>Project#milestones.build, Project#milestones.create</tt>
32
+ # * <tt>Project#categories.empty?, Project#categories.size, Project#categories, Project#categories<<(category1),</tt>
33
+ # <tt>Project#categories.delete(category1)</tt>
34
+ #
35
+ # == Example
36
+ #
37
+ # link:files/examples/associations.png
38
+ #
39
+ # == Is it belongs_to or has_one?
40
+ #
41
+ # Both express a 1-1 relationship, the difference is mostly where to place the foreign key, which goes on the table for the class
42
+ # saying belongs_to. Example:
43
+ #
44
+ # class User < BigRecord::Base
45
+ # # I reference an account.
46
+ # belongs_to :account
47
+ # end
48
+ #
49
+ # class Account < BigRecord::Base
50
+ # # One user references me.
51
+ # has_one :user
52
+ # end
53
+ #
54
+ # The tables for these classes could look something like:
55
+ #
56
+ # CREATE TABLE users (
57
+ # id int(11) NOT NULL auto_increment,
58
+ # account_id int(11) default NULL,
59
+ # name varchar default NULL,
60
+ # PRIMARY KEY (id)
61
+ # )
62
+ #
63
+ # CREATE TABLE accounts (
64
+ # id int(11) NOT NULL auto_increment,
65
+ # name varchar default NULL,
66
+ # PRIMARY KEY (id)
67
+ # )
68
+ #
69
+ # == Unsaved objects and associations
70
+ #
71
+ # You can manipulate objects and associations before they are saved to the database, but there is some special behaviour you should be
72
+ # aware of, mostly involving the saving of associated objects.
73
+ #
74
+ # === One-to-one associations
75
+ #
76
+ # * Assigning an object to a has_one association automatically saves that object and the object being replaced (if there is one), in
77
+ # order to update their primary keys - except if the parent object is unsaved (new_record? == true).
78
+ # * If either of these saves fail (due to one of the objects being invalid) the assignment statement returns false and the assignment
79
+ # is cancelled.
80
+ # * If you wish to assign an object to a has_one association without saving it, use the #association.build method (documented below).
81
+ # * Assigning an object to a belongs_to association does not save the object, since the foreign key field belongs on the parent. It does
82
+ # not save the parent either.
83
+ #
84
+ # === Collections
85
+ #
86
+ # * Adding an object to a collection (has_many or has_and_belongs_to_many) automatically saves that object, except if the parent object
87
+ # (the owner of the collection) is not yet stored in the database.
88
+ # * If saving any of the objects being added to a collection (via #push or similar) fails, then #push returns false.
89
+ # * You can add an object to a collection without automatically saving it by using the #collection.build method (documented below).
90
+ # * All unsaved (new_record? == true) members of the collection are automatically saved when the parent is saved.
91
+ #
92
+ # === Association callbacks
93
+ #
94
+ # Similiar to the normal callbacks that hook into the lifecycle of an Active Record object, you can also define callbacks that get
95
+ # trigged when you add an object to or removing an object from a association collection. Example:
96
+ #
97
+ # class Project
98
+ # has_and_belongs_to_many :developers, :after_add => :evaluate_velocity
99
+ #
100
+ # def evaluate_velocity(developer)
101
+ # ...
102
+ # end
103
+ # end
104
+ #
105
+ # It's possible to stack callbacks by passing them as an array. Example:
106
+ #
107
+ # class Project
108
+ # has_and_belongs_to_many :developers, :after_add => [:evaluate_velocity, Proc.new { |p, d| p.shipping_date = Time.now}]
109
+ # end
110
+ #
111
+ # Possible callbacks are: before_add, after_add, before_remove and after_remove.
112
+ #
113
+ # Should any of the before_add callbacks throw an exception, the object does not get added to the collection. Same with
114
+ # the before_remove callbacks, if an exception is thrown the object doesn't get removed.
115
+ #
116
+ # === Association extensions
117
+ #
118
+ # The proxy objects that controls the access to associations can be extended through anonymous modules. This is especially
119
+ # beneficial for adding new finders, creators, and other factory-type methods that are only used as part of this association.
120
+ # Example:
121
+ #
122
+ # class Account < BigRecord::Base
123
+ # has_many :people do
124
+ # def find_or_create_by_name(name)
125
+ # first_name, last_name = name.split(" ", 2)
126
+ # find_or_create_by_first_name_and_last_name(first_name, last_name)
127
+ # end
128
+ # end
129
+ # end
130
+ #
131
+ # person = Account.find(:first).people.find_or_create_by_name("David Heinemeier Hansson")
132
+ # person.first_name # => "David"
133
+ # person.last_name # => "Heinemeier Hansson"
134
+ #
135
+ # If you need to share the same extensions between many associations, you can use a named extension module. Example:
136
+ #
137
+ # module FindOrCreateByNameExtension
138
+ # def find_or_create_by_name(name)
139
+ # first_name, last_name = name.split(" ", 2)
140
+ # find_or_create_by_first_name_and_last_name(first_name, last_name)
141
+ # end
142
+ # end
143
+ #
144
+ # class Account < BigRecord::Base
145
+ # has_many :people, :extend => FindOrCreateByNameExtension
146
+ # end
147
+ #
148
+ # class Company < BigRecord::Base
149
+ # has_many :people, :extend => FindOrCreateByNameExtension
150
+ # end
151
+ #
152
+ # If you need to use multiple named extension modules, you can specify an array of modules with the :extend option.
153
+ # In the case of name conflicts between methods in the modules, methods in modules later in the array supercede
154
+ # those earlier in the array. Example:
155
+ #
156
+ # class Account < BigRecord::Base
157
+ # has_many :people, :extend => [FindOrCreateByNameExtension, FindRecentExtension]
158
+ # end
159
+ #
160
+ # Some extensions can only be made to work with knowledge of the association proxy's internals.
161
+ # Extensions can access relevant state using accessors on the association proxy:
162
+ #
163
+ # * +proxy_owner+ - Returns the object the association is part of.
164
+ # * +proxy_reflection+ - Returns the reflection object that describes the association.
165
+ # * +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.
166
+ #
167
+ # === Association Join Models
168
+ #
169
+ # Has Many associations can be configured with the :through option to use an explicit join model to retrieve the data. This
170
+ # operates similarly to a <tt>has_and_belongs_to_many</tt> association. The advantage is that you're able to add validations,
171
+ # callbacks, and extra attributes on the join model. Consider the following schema:
172
+ #
173
+ # class Author < BigRecord::Base
174
+ # has_many :authorships
175
+ # has_many :books, :through => :authorships
176
+ # end
177
+ #
178
+ # class Authorship < BigRecord::Base
179
+ # belongs_to :author
180
+ # belongs_to :book
181
+ # end
182
+ #
183
+ # @author = Author.find :first
184
+ # @author.authorships.collect { |a| a.book } # selects all books that the author's authorships belong to.
185
+ # @author.books # selects all books by using the Authorship join model
186
+ #
187
+ # You can also go through a has_many association on the join model:
188
+ #
189
+ # class Firm < BigRecord::Base
190
+ # has_many :clients
191
+ # has_many :invoices, :through => :clients
192
+ # end
193
+ #
194
+ # class Client < BigRecord::Base
195
+ # belongs_to :firm
196
+ # has_many :invoices
197
+ # end
198
+ #
199
+ # class Invoice < BigRecord::Base
200
+ # belongs_to :client
201
+ # end
202
+ #
203
+ # @firm = Firm.find :first
204
+ # @firm.clients.collect { |c| c.invoices }.flatten # select all invoices for all clients of the firm
205
+ # @firm.invoices # selects all invoices by going through the Client join model.
206
+ #
207
+ # === Polymorphic Associations
208
+ #
209
+ # Polymorphic associations on models are not restricted on what types of models they can be associated with. Rather, they
210
+ # specify an interface that a has_many association must adhere to.
211
+ #
212
+ # class Asset < BigRecord::Base
213
+ # belongs_to :attachable, :polymorphic => true
214
+ # end
215
+ #
216
+ # class Post < BigRecord::Base
217
+ # has_many :assets, :as => :attachable # The <tt>:as</tt> option specifies the polymorphic interface to use.
218
+ # end
219
+ #
220
+ # @asset.attachable = @post
221
+ #
222
+ # 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
223
+ # an attachable_id integer column and an attachable_type string column.
224
+ #
225
+ # Using polymorphic associations in combination with single table inheritance (STI) is a little tricky. In order
226
+ # for the associations to work as expected, ensure that you store the base model for the STI models in the
227
+ # type column of the polymorphic association. To continue with the asset example above, suppose there are guest posts
228
+ # and member posts that use the posts table for STI. So there will be an additional 'type' column in the posts table.
229
+ #
230
+ # class Asset < BigRecord::Base
231
+ # belongs_to :attachable, :polymorphic => true
232
+ #
233
+ # def attachable_type=(sType)
234
+ # super(sType.to_s.classify.constantize.base_class.to_s)
235
+ # end
236
+ # end
237
+ #
238
+ # class Post < BigRecord::Base
239
+ # # because we store "Post" in attachable_type now :dependent => :destroy will work
240
+ # has_many :assets, :as => :attachable, :dependent => :destroy
241
+ # end
242
+ #
243
+ # class GuestPost < BigRecord::Base
244
+ # end
245
+ #
246
+ # class MemberPost < BigRecord::Base
247
+ # end
248
+ #
249
+ # == Caching
250
+ #
251
+ # All of the methods are built on a simple caching principle that will keep the result of the last query around unless specifically
252
+ # instructed not to. The cache is even shared across methods to make it even cheaper to use the macro-added methods without
253
+ # worrying too much about performance at the first go. Example:
254
+ #
255
+ # project.milestones # fetches milestones from the database
256
+ # project.milestones.size # uses the milestone cache
257
+ # project.milestones.empty? # uses the milestone cache
258
+ # project.milestones(true).size # fetches milestones from the database
259
+ # project.milestones # uses the milestone cache
260
+ #
261
+ # == Eager loading of associations
262
+ #
263
+ # Eager loading is a way to find objects of a certain class and a number of named associations along with it in a single SQL call. This is
264
+ # one of the easiest ways of to prevent the dreaded 1+N problem in which fetching 100 posts that each needs to display their author
265
+ # triggers 101 database queries. Through the use of eager loading, the 101 queries can be reduced to 1. Example:
266
+ #
267
+ # class Post < BigRecord::Base
268
+ # belongs_to :author
269
+ # has_many :comments
270
+ # end
271
+ #
272
+ # Consider the following loop using the class above:
273
+ #
274
+ # for post in Post.find(:all)
275
+ # puts "Post: " + post.title
276
+ # puts "Written by: " + post.author.name
277
+ # puts "Last comment on: " + post.comments.first.created_on
278
+ # end
279
+ #
280
+ # To iterate over these one hundred posts, we'll generate 201 database queries. Let's first just optimize it for retrieving the author:
281
+ #
282
+ # for post in Post.find(:all, :include => :author)
283
+ #
284
+ # This references the name of the belongs_to association that also used the :author symbol, so the find will now weave in a join something
285
+ # like this: LEFT OUTER JOIN authors ON authors.id = posts.author_id. Doing so will cut down the number of queries from 201 to 101.
286
+ #
287
+ # We can improve upon the situation further by referencing both associations in the finder with:
288
+ #
289
+ # for post in Post.find(:all, :include => [ :author, :comments ])
290
+ #
291
+ # That'll add another join along the lines of: LEFT OUTER JOIN comments ON comments.post_id = posts.id. And we'll be down to 1 query.
292
+ # But that shouldn't fool you to think that you can pull out huge amounts of data with no performance penalty just because you've reduced
293
+ # 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
294
+ # 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.
295
+ #
296
+ # Since the eager loading pulls from multiple tables, you'll have to disambiguate any column references in both conditions and orders. So
297
+ # :order => "posts.id DESC" will work while :order => "id DESC" will not. Because eager loading generates the SELECT statement too, the
298
+ # :select option is ignored.
299
+ #
300
+ # You can use eager loading on multiple associations from the same table, but you cannot use those associations in orders and conditions
301
+ # as there is currently not any way to disambiguate them. Eager loading will not pull additional attributes on join tables, so "rich
302
+ # associations" with has_and_belongs_to_many are not a good fit for eager loading.
303
+ #
304
+ # When eager loaded, conditions are interpolated in the context of the model class, not the model instance. Conditions are lazily interpolated
305
+ # before the actual model exists.
306
+ #
307
+ # == Table Aliasing
308
+ #
309
+ # BigRecord uses table aliasing in the case that a table is referenced multiple times in a join. If a table is referenced only once,
310
+ # the standard table name is used. The second time, the table is aliased as #{reflection_name}_#{parent_table_name}. Indexes are appended
311
+ # for any more successive uses of the table name.
312
+ #
313
+ # Post.find :all, :include => :comments
314
+ # # => SELECT ... FROM posts LEFT OUTER JOIN comments ON ...
315
+ # Post.find :all, :include => :special_comments # STI
316
+ # # => SELECT ... FROM posts LEFT OUTER JOIN comments ON ... AND comments.type = 'SpecialComment'
317
+ # Post.find :all, :include => [:comments, :special_comments] # special_comments is the reflection name, posts is the parent table name
318
+ # # => SELECT ... FROM posts LEFT OUTER JOIN comments ON ... LEFT OUTER JOIN comments special_comments_posts
319
+ #
320
+ # Acts as tree example:
321
+ #
322
+ # TreeMixin.find :all, :include => :children
323
+ # # => SELECT ... FROM mixins LEFT OUTER JOIN mixins childrens_mixins ...
324
+ # TreeMixin.find :all, :include => {:children => :parent} # using cascading eager includes
325
+ # # => SELECT ... FROM mixins LEFT OUTER JOIN mixins childrens_mixins ...
326
+ # LEFT OUTER JOIN parents_mixins ...
327
+ # TreeMixin.find :all, :include => {:children => {:parent => :children}}
328
+ # # => SELECT ... FROM mixins LEFT OUTER JOIN mixins childrens_mixins ...
329
+ # LEFT OUTER JOIN parents_mixins ...
330
+ # LEFT OUTER JOIN mixins childrens_mixins_2
331
+ #
332
+ # Has and Belongs to Many join tables use the same idea, but add a _join suffix:
333
+ #
334
+ # Post.find :all, :include => :categories
335
+ # # => SELECT ... FROM posts LEFT OUTER JOIN categories_posts ... LEFT OUTER JOIN categories ...
336
+ # Post.find :all, :include => {:categories => :posts}
337
+ # # => SELECT ... FROM posts LEFT OUTER JOIN categories_posts ... LEFT OUTER JOIN categories ...
338
+ # LEFT OUTER JOIN categories_posts posts_categories_join LEFT OUTER JOIN posts posts_categories
339
+ # Post.find :all, :include => {:categories => {:posts => :categories}}
340
+ # # => SELECT ... FROM posts LEFT OUTER JOIN categories_posts ... LEFT OUTER JOIN categories ...
341
+ # LEFT OUTER JOIN categories_posts posts_categories_join LEFT OUTER JOIN posts posts_categories
342
+ # LEFT OUTER JOIN categories_posts categories_posts_join LEFT OUTER JOIN categories categories_posts
343
+ #
344
+ # If you wish to specify your own custom joins using a :joins option, those table names will take precedence over the eager associations..
345
+ #
346
+ # Post.find :all, :include => :comments, :joins => "inner join comments ..."
347
+ # # => SELECT ... FROM posts LEFT OUTER JOIN comments_posts ON ... INNER JOIN comments ...
348
+ # Post.find :all, :include => [:comments, :special_comments], :joins => "inner join comments ..."
349
+ # # => SELECT ... FROM posts LEFT OUTER JOIN comments comments_posts ON ...
350
+ # LEFT OUTER JOIN comments special_comments_posts ...
351
+ # INNER JOIN comments ...
352
+ #
353
+ # Table aliases are automatically truncated according to the maximum length of table identifiers according to the specific database.
354
+ #
355
+ # == Modules
356
+ #
357
+ # By default, associations will look for objects within the current module scope. Consider:
358
+ #
359
+ # module MyApplication
360
+ # module Business
361
+ # class Firm < BigRecord::Base
362
+ # has_many :clients
363
+ # end
364
+ #
365
+ # class Company < BigRecord::Base; end
366
+ # end
367
+ # end
368
+ #
369
+ # When Firm#clients is called, it'll in turn call <tt>MyApplication::Business::Company.find(firm.id)</tt>. If you want to associate
370
+ # with a class in another module scope this can be done by specifying the complete class name, such as:
371
+ #
372
+ # module MyApplication
373
+ # module Business
374
+ # class Firm < BigRecord::Base; end
375
+ # end
376
+ #
377
+ # module Billing
378
+ # class Account < BigRecord::Base
379
+ # belongs_to :firm, :class_name => "MyApplication::Business::Firm"
380
+ # end
381
+ # end
382
+ # end
383
+ #
384
+ # == Type safety with BigRecord::AssociationTypeMismatch
385
+ #
386
+ # If you attempt to assign an object to an association that doesn't match the inferred or specified <tt>:class_name</tt>, you'll
387
+ # get a BigRecord::AssociationTypeMismatch.
388
+ #
389
+ # == Options
390
+ #
391
+ # All of the association macros can be specialized through options which makes more complex cases than the simple and guessable ones
392
+ # possible.
393
+ module ClassMethods
394
+ # Adds the following methods for retrieval and query of collections of associated objects.
395
+ # +collection+ is replaced with the symbol passed as the first argument, so
396
+ # <tt>has_many :clients</tt> would add among others <tt>clients.empty?</tt>.
397
+ # * <tt>collection(force_reload = false)</tt> - returns an array of all the associated objects.
398
+ # An empty array is returned if none are found.
399
+ # * <tt>collection<<(object, ...)</tt> - adds one or more objects to the collection by setting their foreign keys to the collection's primary key.
400
+ # * <tt>collection.delete(object, ...)</tt> - removes one or more objects from the collection by setting their foreign keys to NULL.
401
+ # This will also destroy the objects if they're declared as belongs_to and dependent on this model.
402
+ # * <tt>collection=objects</tt> - replaces the collections content by deleting and adding objects as appropriate.
403
+ # * <tt>collection_singular_ids</tt> - returns an array of the associated objects ids
404
+ # * <tt>collection_singular_ids=ids</tt> - replace the collection by the objects identified by the primary keys in +ids+
405
+ # * <tt>collection.clear</tt> - removes every object from the collection. This destroys the associated objects if they
406
+ # are <tt>:dependent</tt>, deletes them directly from the database if they are <tt>:dependent => :delete_all</tt>,
407
+ # and sets their foreign keys to NULL otherwise.
408
+ # * <tt>collection.empty?</tt> - returns true if there are no associated objects.
409
+ # * <tt>collection.size</tt> - returns the number of associated objects.
410
+ # * <tt>collection.find</tt> - finds an associated object according to the same rules as Base.find.
411
+ # * <tt>collection.build(attributes = {})</tt> - returns a new object of the collection type that has been instantiated
412
+ # with +attributes+ and linked to this object through a foreign key but has not yet been saved. *Note:* This only works if an
413
+ # associated object already exists, not if it's nil!
414
+ # * <tt>collection.create(attributes = {})</tt> - returns a new object of the collection type that has been instantiated
415
+ # with +attributes+ and linked to this object through a foreign key and that has already been saved (if it passed the validation).
416
+ # *Note:* This only works if an associated object already exists, not if it's nil!
417
+ #
418
+ # Example: A Firm class declares <tt>has_many :clients</tt>, which will add:
419
+ # * <tt>Firm#clients</tt> (similar to <tt>Clients.find :all, :conditions => "firm_id = #{id}"</tt>)
420
+ # * <tt>Firm#clients<<</tt>
421
+ # * <tt>Firm#clients.delete</tt>
422
+ # * <tt>Firm#clients=</tt>
423
+ # * <tt>Firm#client_ids</tt>
424
+ # * <tt>Firm#client_ids=</tt>
425
+ # * <tt>Firm#clients.clear</tt>
426
+ # * <tt>Firm#clients.empty?</tt> (similar to <tt>firm.clients.size == 0</tt>)
427
+ # * <tt>Firm#clients.size</tt> (similar to <tt>Client.count "firm_id = #{id}"</tt>)
428
+ # * <tt>Firm#clients.find</tt> (similar to <tt>Client.find(id, :conditions => "firm_id = #{id}")</tt>)
429
+ # * <tt>Firm#clients.build</tt> (similar to <tt>Client.new("firm_id" => id)</tt>)
430
+ # * <tt>Firm#clients.create</tt> (similar to <tt>c = Client.new("firm_id" => id); c.save; c</tt>)
431
+ # The declaration can also include an options hash to specialize the behavior of the association.
432
+ #
433
+ # Options are:
434
+ # * <tt>:class_name</tt> - specify the class name of the association. Use it only if that name can't be inferred
435
+ # from the association name. So <tt>has_many :products</tt> will by default be linked to the +Product+ class, but
436
+ # if the real class name is +SpecialProduct+, you'll have to specify it with this option.
437
+ # * <tt>:conditions</tt> - specify the conditions that the associated objects must meet in order to be included as a "WHERE"
438
+ # sql fragment, such as "price > 5 AND name LIKE 'B%'".
439
+ # * <tt>:order</tt> - specify the order in which the associated objects are returned as a "ORDER BY" sql fragment,
440
+ # such as "last_name, first_name DESC"
441
+ # * <tt>:group</tt> - specify the attribute by which the associated objects are returned as a "GROUP BY" sql fragment,
442
+ # such as "category"
443
+ # * <tt>:foreign_key</tt> - specify the foreign key used for the association. By default this is guessed to be the name
444
+ # of this class in lower-case and "_id" suffixed. So a +Person+ class that makes a has_many association will use "person_id"
445
+ # as the default foreign_key.
446
+ # * <tt>:dependent</tt> - if set to :destroy all the associated objects are destroyed
447
+ # alongside this object by calling their destroy method. If set to :delete_all all associated
448
+ # objects are deleted *without* calling their destroy method. If set to :nullify all associated
449
+ # objects' foreign keys are set to NULL *without* calling their save callbacks.
450
+ # NOTE: :dependent => true is deprecated and has been replaced with :dependent => :destroy.
451
+ # May not be set if :exclusively_dependent is also set.
452
+ # * <tt>:exclusively_dependent</tt> - Deprecated; equivalent to :dependent => :delete_all. If set to true all
453
+ # the associated object are deleted in one SQL statement without having their
454
+ # before_destroy callback run. This should only be used on associations that depend solely on this class and don't need to do any
455
+ # clean-up in before_destroy. The upside is that it's much faster, especially if there's a counter_cache involved.
456
+ # May not be set if :dependent is also set.
457
+ # * <tt>:finder_sql</tt> - specify a complete SQL statement to fetch the association. This is a good way to go for complex
458
+ # associations that depend on multiple tables. Note: When this option is used, +find_in_collection+ is _not_ added.
459
+ # * <tt>:counter_sql</tt> - specify a complete SQL statement to fetch the size of the association. If +:finder_sql+ is
460
+ # specified but +:counter_sql+, +:counter_sql+ will be generated by replacing SELECT ... FROM with SELECT COUNT(*) FROM.
461
+ # * <tt>:extend</tt> - specify a named module for extending the proxy, see "Association extensions".
462
+ # * <tt>:include</tt> - specify second-order associations that should be eager loaded when the collection is loaded.
463
+ # * <tt>:group</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
464
+ # * <tt>:limit</tt>: An integer determining the limit on the number of rows that should be returned.
465
+ # * <tt>:offset</tt>: An integer determining the offset from where the rows should be fetched. So at 5, it would skip the first 4 rows.
466
+ # * <tt>:select</tt>: By default, this is * as in SELECT * FROM, but can be changed if you for example want to do a join, but not
467
+ # include the joined columns.
468
+ # * <tt>:as</tt>: Specifies a polymorphic interface (See #belongs_to).
469
+ # * <tt>:through</tt>: Specifies a Join Model to perform the query through. Options for <tt>:class_name</tt> and <tt>:foreign_key</tt>
470
+ # are ignored, as the association uses the source reflection. You can only use a <tt>:through</tt> query through a <tt>belongs_to</tt>
471
+ # or <tt>has_many</tt> association.
472
+ # * <tt>:source</tt>: Specifies the source association name used by <tt>has_many :through</tt> queries. Only use it if the name cannot be
473
+ # inferred from the association. <tt>has_many :subscribers, :through => :subscriptions</tt> will look for either +:subscribers+ or
474
+ # +:subscriber+ on +Subscription+, unless a +:source+ is given.
475
+ # * <tt>:source_type</tt>: Specifies type of the source association used by <tt>has_many :through</tt> queries where the source association
476
+ # is a polymorphic belongs_to.
477
+ # * <tt>:uniq</tt> - if set to true, duplicates will be omitted from the collection. Useful in conjunction with :through.
478
+ #
479
+ # Option examples:
480
+ # has_many :comments, :order => "posted_on"
481
+ # has_many :comments, :include => :author
482
+ # has_many :people, :class_name => "Person", :conditions => "deleted = 0", :order => "name"
483
+ # has_many :tracks, :order => "position", :dependent => :destroy
484
+ # has_many :comments, :dependent => :nullify
485
+ # has_many :tags, :as => :taggable
486
+ # has_many :subscribers, :through => :subscriptions, :source => :user
487
+ # has_many :subscribers, :class_name => "Person", :finder_sql =>
488
+ # 'SELECT DISTINCT people.* ' +
489
+ # 'FROM people p, post_subscriptions ps ' +
490
+ # 'WHERE ps.post_id = #{id} AND ps.person_id = p.id ' +
491
+ # 'ORDER BY p.first_name'
492
+ def has_many_big_records(association_id, options = {}, &extension)
493
+ reflection = create_has_many_big_records_reflection(association_id, options, &extension)
494
+
495
+ configure_dependency_for_has_many(reflection)
496
+
497
+ if options[:through]
498
+ collection_reader_method(reflection, HasManyThroughAssociation)
499
+ else
500
+ add_association_callbacks(reflection.name, reflection.options)
501
+ collection_accessor_methods(reflection, HasManyAssociation)
502
+ end
503
+
504
+ # add_deprecated_api_for_has_many(reflection.name)
505
+ end
506
+
507
+ alias_method :has_many_bigrecords, :has_many_big_records
508
+
509
+ # Adds the following methods for retrieval and query of a single associated object.
510
+ # +association+ is replaced with the symbol passed as the first argument, so
511
+ # <tt>has_one :manager</tt> would add among others <tt>manager.nil?</tt>.
512
+ # * <tt>association(force_reload = false)</tt> - returns the associated object. Nil is returned if none is found.
513
+ # * <tt>association=(associate)</tt> - assigns the associate object, extracts the primary key, sets it as the foreign key,
514
+ # and saves the associate object.
515
+ # * <tt>association.nil?</tt> - returns true if there is no associated object.
516
+ # * <tt>build_association(attributes = {})</tt> - returns a new object of the associated type that has been instantiated
517
+ # with +attributes+ and linked to this object through a foreign key but has not yet been saved. Note: This ONLY works if
518
+ # an association already exists. It will NOT work if the association is nil.
519
+ # * <tt>create_association(attributes = {})</tt> - returns a new object of the associated type that has been instantiated
520
+ # with +attributes+ and linked to this object through a foreign key and that has already been saved (if it passed the validation).
521
+ #
522
+ # Example: An Account class declares <tt>has_one :beneficiary</tt>, which will add:
523
+ # * <tt>Account#beneficiary</tt> (similar to <tt>Beneficiary.find(:first, :conditions => "account_id = #{id}")</tt>)
524
+ # * <tt>Account#beneficiary=(beneficiary)</tt> (similar to <tt>beneficiary.account_id = account.id; beneficiary.save</tt>)
525
+ # * <tt>Account#beneficiary.nil?</tt>
526
+ # * <tt>Account#build_beneficiary</tt> (similar to <tt>Beneficiary.new("account_id" => id)</tt>)
527
+ # * <tt>Account#create_beneficiary</tt> (similar to <tt>b = Beneficiary.new("account_id" => id); b.save; b</tt>)
528
+ #
529
+ # The declaration can also include an options hash to specialize the behavior of the association.
530
+ #
531
+ # Options are:
532
+ # * <tt>:class_name</tt> - specify the class name of the association. Use it only if that name can't be inferred
533
+ # from the association name. So <tt>has_one :manager</tt> will by default be linked to the +Manager+ class, but
534
+ # if the real class name is +Person+, you'll have to specify it with this option.
535
+ # * <tt>:conditions</tt> - specify the conditions that the associated object must meet in order to be included as a "WHERE"
536
+ # sql fragment, such as "rank = 5".
537
+ # * <tt>:order</tt> - specify the order from which the associated object will be picked at the top. Specified as
538
+ # an "ORDER BY" sql fragment, such as "last_name, first_name DESC"
539
+ # * <tt>:dependent</tt> - if set to :destroy (or true) the associated object is destroyed when this object is. If set to
540
+ # :delete the associated object is deleted *without* calling its destroy method. If set to :nullify the associated
541
+ # object's foreign key is set to NULL. Also, association is assigned.
542
+ # * <tt>:foreign_key</tt> - specify the foreign key used for the association. By default this is guessed to be the name
543
+ # of this class in lower-case and "_id" suffixed. So a +Person+ class that makes a has_one association will use "person_id"
544
+ # as the default foreign_key.
545
+ # * <tt>:include</tt> - specify second-order associations that should be eager loaded when this object is loaded.
546
+ # * <tt>:as</tt>: Specifies a polymorphic interface (See #belongs_to).
547
+ #
548
+ # Option examples:
549
+ # has_one :credit_card, :dependent => :destroy # destroys the associated credit card
550
+ # has_one :credit_card, :dependent => :nullify # updates the associated records foriegn key value to null rather than destroying it
551
+ # has_one :last_comment, :class_name => "Comment", :order => "posted_on"
552
+ # has_one :project_manager, :class_name => "Person", :conditions => "role = 'project_manager'"
553
+ # has_one :attachment, :as => :attachable
554
+ def has_one_big_record(association_id, options = {})
555
+ reflection = create_has_one_big_record_reflection(association_id, options)
556
+
557
+ module_eval do
558
+ after_save <<-EOF
559
+ association = instance_variable_get("@#{reflection.name}")
560
+ if !association.nil? && (new_record? || association.new_record? || association["#{reflection.primary_key_name}"] != id)
561
+ association["#{reflection.primary_key_name}"] = id
562
+ association.save(true)
563
+ end
564
+ EOF
565
+ end
566
+
567
+ association_accessor_methods_big_record(reflection, HasOneAssociation)
568
+ association_constructor_method_big_record(:build, reflection, HasOneAssociation)
569
+ association_constructor_method_big_record(:create, reflection, HasOneAssociation)
570
+
571
+ configure_dependency_for_has_one(reflection)
572
+
573
+ # deprecated api
574
+ # deprecated_has_association_method(reflection.name)
575
+ # deprecated_association_comparison_method(reflection.name, reflection.class_name)
576
+ end
577
+
578
+ alias_method :has_one_bigrecord, :has_one_big_record
579
+
580
+ # Adds the following methods for retrieval and query for a single associated object that this object holds an id to.
581
+ # +association+ is replaced with the symbol passed as the first argument, so
582
+ # <tt>belongs_to :author</tt> would add among others <tt>author.nil?</tt>.
583
+ # * <tt>association(force_reload = false)</tt> - returns the associated object. Nil is returned if none is found.
584
+ # * <tt>association=(associate)</tt> - assigns the associate object, extracts the primary key, and sets it as the foreign key.
585
+ # * <tt>association.nil?</tt> - returns true if there is no associated object.
586
+ # * <tt>build_association(attributes = {})</tt> - returns a new object of the associated type that has been instantiated
587
+ # with +attributes+ and linked to this object through a foreign key but has not yet been saved.
588
+ # * <tt>create_association(attributes = {})</tt> - returns a new object of the associated type that has been instantiated
589
+ # with +attributes+ and linked to this object through a foreign key and that has already been saved (if it passed the validation).
590
+ #
591
+ # Example: A Post class declares <tt>belongs_to :author</tt>, which will add:
592
+ # * <tt>Post#author</tt> (similar to <tt>Author.find(author_id)</tt>)
593
+ # * <tt>Post#author=(author)</tt> (similar to <tt>post.author_id = author.id</tt>)
594
+ # * <tt>Post#author?</tt> (similar to <tt>post.author == some_author</tt>)
595
+ # * <tt>Post#author.nil?</tt>
596
+ # * <tt>Post#build_author</tt> (similar to <tt>post.author = Author.new</tt>)
597
+ # * <tt>Post#create_author</tt> (similar to <tt>post.author = Author.new; post.author.save; post.author</tt>)
598
+ # The declaration can also include an options hash to specialize the behavior of the association.
599
+ #
600
+ # Options are:
601
+ # * <tt>:class_name</tt> - specify the class name of the association. Use it only if that name can't be inferred
602
+ # from the association name. So <tt>has_one :author</tt> will by default be linked to the +Author+ class, but
603
+ # if the real class name is +Person+, you'll have to specify it with this option.
604
+ # * <tt>:conditions</tt> - specify the conditions that the associated object must meet in order to be included as a "WHERE"
605
+ # sql fragment, such as "authorized = 1".
606
+ # * <tt>:order</tt> - specify the order from which the associated object will be picked at the top. Specified as
607
+ # an "ORDER BY" sql fragment, such as "last_name, first_name DESC"
608
+ # * <tt>:foreign_key</tt> - specify the foreign key used for the association. By default this is guessed to be the name
609
+ # of the associated class in lower-case and "_id" suffixed. So a +Person+ class that makes a belongs_to association to a
610
+ # +Boss+ class will use "boss_id" as the default foreign_key.
611
+ # * <tt>:counter_cache</tt> - caches the number of belonging objects on the associate class through use of increment_counter
612
+ # and decrement_counter. The counter cache is incremented when an object of this class is created and decremented when it's
613
+ # destroyed. This requires that a column named "#{table_name}_count" (such as comments_count for a belonging Comment class)
614
+ # is used on the associate class (such as a Post class). You can also specify a custom counter cache column by given that
615
+ # name instead of a true/false value to this option (e.g., <tt>:counter_cache => :my_custom_counter</tt>.)
616
+ # * <tt>:include</tt> - specify second-order associations that should be eager loaded when this object is loaded.
617
+ # * <tt>:polymorphic</tt> - specify this association is a polymorphic association by passing true.
618
+ #
619
+ # Option examples:
620
+ # belongs_to :firm, :foreign_key => "client_of"
621
+ # belongs_to :author, :class_name => "Person", :foreign_key => "author_id"
622
+ # belongs_to :valid_coupon, :class_name => "Coupon", :foreign_key => "coupon_id",
623
+ # :conditions => 'discounts > #{payments_count}'
624
+ # belongs_to :attachable, :polymorphic => true
625
+ def belongs_to_big_record(association_id, options = {})
626
+ if options.include?(:class_name) && !options.include?(:foreign_key)
627
+ ::ActiveSupport::Deprecation.warn(
628
+ "The inferred foreign_key name will change in Rails 2.0 to use the association name instead of its class name when they differ. When using :class_name in belongs_to, use the :foreign_key option to explicitly set the key name to avoid problems in the transition.",
629
+ caller)
630
+ end
631
+
632
+ reflection = create_belongs_to_big_record_reflection(association_id, options)
633
+
634
+ if reflection.options[:polymorphic]
635
+ association_accessor_methods_big_record(reflection, BelongsToPolymorphicAssociation)
636
+
637
+ module_eval do
638
+ before_save <<-EOF
639
+ association = instance_variable_get("@#{reflection.name}")
640
+ if association && association.target
641
+ if association.new_record?
642
+ association.save(true)
643
+ end
644
+
645
+ if association.updated?
646
+ self["#{reflection.primary_key_name}"] = association.id
647
+ self["#{reflection.options[:foreign_type]}"] = association.class.base_class.name.to_s
648
+ end
649
+ end
650
+ EOF
651
+ end
652
+ else
653
+ association_accessor_methods_big_record(reflection, BelongsToAssociation)
654
+ association_constructor_method_big_record(:build, reflection, BelongsToAssociation)
655
+ association_constructor_method_big_record(:create, reflection, BelongsToAssociation)
656
+
657
+ module_eval do
658
+ before_save <<-EOF
659
+ association = instance_variable_get("@#{reflection.name}")
660
+ if !association.nil?
661
+ if association.new_record?
662
+ association.save(true)
663
+ end
664
+
665
+ if association.updated?
666
+ self["#{reflection.primary_key_name}"] = association.id
667
+ end
668
+ end
669
+ EOF
670
+ end
671
+
672
+ # deprecated api
673
+ # deprecated_has_association_method(reflection.name)
674
+ # deprecated_association_comparison_method(reflection.name, reflection.class_name)
675
+ end
676
+
677
+ if options[:counter_cache]
678
+ cache_column = options[:counter_cache] == true ?
679
+ "#{self.to_s.underscore.pluralize}_count" :
680
+ options[:counter_cache]
681
+
682
+ module_eval(
683
+ "after_create '#{reflection.name}.class.increment_counter(\"#{cache_column}\", #{reflection.primary_key_name})" +
684
+ " unless #{reflection.name}.nil?'"
685
+ )
686
+
687
+ module_eval(
688
+ "before_destroy '#{reflection.name}.class.decrement_counter(\"#{cache_column}\", #{reflection.primary_key_name})" +
689
+ " unless #{reflection.name}.nil?'"
690
+ )
691
+ end
692
+ end
693
+
694
+ alias_method :belongs_to_bigrecord, :belongs_to_big_record
695
+
696
+ def belongs_to_many(association_id, options = {})
697
+ if options.include?(:class_name) && !options.include?(:foreign_key)
698
+ ::ActiveSupport::Deprecation.warn(
699
+ "The inferred foreign_key name will change in Rails 2.0 to use the association name instead of its class name when they differ. When using :class_name in belongs_to, use the :foreign_key option to explicitly set the key name to avoid problems in the transition.",
700
+ caller)
701
+ end
702
+
703
+ reflection = create_belongs_to_many_reflection(association_id, options)
704
+
705
+ association_accessor_methods_big_record(reflection, BelongsToManyAssociation)
706
+ association_constructor_method_big_record(:build, reflection, BelongsToManyAssociation)
707
+ association_constructor_method_big_record(:create, reflection, BelongsToManyAssociation)
708
+
709
+ module_eval do
710
+ before_save <<-EOF
711
+ association = instance_variable_get("@#{reflection.name}")
712
+ if !association.nil?
713
+ association.each do |r|
714
+ r.save(true) if r.new_record?
715
+ end
716
+
717
+ if association.updated?
718
+ self["#{reflection.primary_key_name}"] = association.collect{|r| r.id}
719
+ end
720
+ end
721
+ EOF
722
+ end
723
+
724
+ end
725
+
726
+ # Associates two classes via an intermediate join table. Unless the join table is explicitly specified as
727
+ # an option, it is guessed using the lexical order of the class names. So a join between Developer and Project
728
+ # will give the default join table name of "developers_projects" because "D" outranks "P". Note that this precedence
729
+ # is calculated using the <tt><</tt> operator for <tt>String</tt>. This means that if the strings are of different lengths,
730
+ # and the strings are equal when compared up to the shortest length, then the longer string is considered of higher
731
+ # lexical precedence than the shorter one. For example, one would expect the tables <tt>paper_boxes</tt> and <tt>papers</tt>
732
+ # to generate a join table name of <tt>papers_paper_boxes</tt> because of the length of the name <tt>paper_boxes</tt>,
733
+ # but it in fact generates a join table name of <tt>paper_boxes_papers</tt>. Be aware of this caveat, and use the
734
+ # custom <tt>join_table</tt> option if you need to.
735
+ #
736
+ # Deprecated: Any additional fields added to the join table will be placed as attributes when pulling records out through
737
+ # has_and_belongs_to_many associations. Records returned from join tables with additional attributes will be marked as
738
+ # ReadOnly (because we can't save changes to the additional attrbutes). It's strongly recommended that you upgrade any
739
+ # associations with attributes to a real join model (see introduction).
740
+ #
741
+ # Adds the following methods for retrieval and query.
742
+ # +collection+ is replaced with the symbol passed as the first argument, so
743
+ # <tt>has_and_belongs_to_many :categories</tt> would add among others <tt>categories.empty?</tt>.
744
+ # * <tt>collection(force_reload = false)</tt> - returns an array of all the associated objects.
745
+ # An empty array is returned if none is found.
746
+ # * <tt>collection<<(object, ...)</tt> - adds one or more objects to the collection by creating associations in the join table
747
+ # (collection.push and collection.concat are aliases to this method).
748
+ # * <tt>collection.push_with_attributes(object, join_attributes)</tt> - adds one to the collection by creating an association in the join table that
749
+ # also holds the attributes from <tt>join_attributes</tt> (should be a hash with the column names as keys). This can be used to have additional
750
+ # attributes on the join, which will be injected into the associated objects when they are retrieved through the collection.
751
+ # (collection.concat_with_attributes is an alias to this method). This method is now deprecated.
752
+ # * <tt>collection.delete(object, ...)</tt> - removes one or more objects from the collection by removing their associations from the join table.
753
+ # This does not destroy the objects.
754
+ # * <tt>collection=objects</tt> - replaces the collections content by deleting and adding objects as appropriate.
755
+ # * <tt>collection_singular_ids</tt> - returns an array of the associated objects ids
756
+ # * <tt>collection_singular_ids=ids</tt> - replace the collection by the objects identified by the primary keys in +ids+
757
+ # * <tt>collection.clear</tt> - removes every object from the collection. This does not destroy the objects.
758
+ # * <tt>collection.empty?</tt> - returns true if there are no associated objects.
759
+ # * <tt>collection.size</tt> - returns the number of associated objects.
760
+ # * <tt>collection.find(id)</tt> - finds an associated object responding to the +id+ and that
761
+ # meets the condition that it has to be associated with this object.
762
+ # * <tt>collection.build(attributes = {})</tt> - returns a new object of the collection type that has been instantiated
763
+ # with +attributes+ and linked to this object through the join table but has not yet been saved.
764
+ # * <tt>collection.create(attributes = {})</tt> - returns a new object of the collection type that has been instantiated
765
+ # with +attributes+ and linked to this object through the join table and that has already been saved (if it passed the validation).
766
+ #
767
+ # Example: An Developer class declares <tt>has_and_belongs_to_many :projects</tt>, which will add:
768
+ # * <tt>Developer#projects</tt>
769
+ # * <tt>Developer#projects<<</tt>
770
+ # * <tt>Developer#projects.delete</tt>
771
+ # * <tt>Developer#projects=</tt>
772
+ # * <tt>Developer#project_ids</tt>
773
+ # * <tt>Developer#project_ids=</tt>
774
+ # * <tt>Developer#projects.clear</tt>
775
+ # * <tt>Developer#projects.empty?</tt>
776
+ # * <tt>Developer#projects.size</tt>
777
+ # * <tt>Developer#projects.find(id)</tt>
778
+ # * <tt>Developer#projects.build</tt> (similar to <tt>Project.new("project_id" => id)</tt>)
779
+ # * <tt>Developer#projects.create</tt> (similar to <tt>c = Project.new("project_id" => id); c.save; c</tt>)
780
+ # The declaration may include an options hash to specialize the behavior of the association.
781
+ #
782
+ # Options are:
783
+ # * <tt>:class_name</tt> - specify the class name of the association. Use it only if that name can't be inferred
784
+ # from the association name. So <tt>has_and_belongs_to_many :projects</tt> will by default be linked to the
785
+ # +Project+ class, but if the real class name is +SuperProject+, you'll have to specify it with this option.
786
+ # * <tt>:join_table</tt> - specify the name of the join table if the default based on lexical order isn't what you want.
787
+ # WARNING: If you're overwriting the table name of either class, the table_name method MUST be declared underneath any
788
+ # has_and_belongs_to_many declaration in order to work.
789
+ # * <tt>:foreign_key</tt> - specify the foreign key used for the association. By default this is guessed to be the name
790
+ # of this class in lower-case and "_id" suffixed. So a +Person+ class that makes a has_and_belongs_to_many association
791
+ # will use "person_id" as the default foreign_key.
792
+ # * <tt>:association_foreign_key</tt> - specify the association foreign key used for the association. By default this is
793
+ # guessed to be the name of the associated class in lower-case and "_id" suffixed. So if the associated class is +Project+,
794
+ # the has_and_belongs_to_many association will use "project_id" as the default association foreign_key.
795
+ # * <tt>:conditions</tt> - specify the conditions that the associated object must meet in order to be included as a "WHERE"
796
+ # sql fragment, such as "authorized = 1".
797
+ # * <tt>:order</tt> - specify the order in which the associated objects are returned as a "ORDER BY" sql fragment, such as "last_name, first_name DESC"
798
+ # * <tt>:uniq</tt> - if set to true, duplicate associated objects will be ignored by accessors and query methods
799
+ # * <tt>:finder_sql</tt> - overwrite the default generated SQL used to fetch the association with a manual one
800
+ # * <tt>:delete_sql</tt> - overwrite the default generated SQL used to remove links between the associated
801
+ # classes with a manual one
802
+ # * <tt>:insert_sql</tt> - overwrite the default generated SQL used to add links between the associated classes
803
+ # with a manual one
804
+ # * <tt>:extend</tt> - anonymous module for extending the proxy, see "Association extensions".
805
+ # * <tt>:include</tt> - specify second-order associations that should be eager loaded when the collection is loaded.
806
+ # * <tt>:group</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
807
+ # * <tt>:limit</tt>: An integer determining the limit on the number of rows that should be returned.
808
+ # * <tt>:offset</tt>: An integer determining the offset from where the rows should be fetched. So at 5, it would skip the first 4 rows.
809
+ # * <tt>:select</tt>: By default, this is * as in SELECT * FROM, but can be changed if you for example want to do a join, but not
810
+ # include the joined columns.
811
+ #
812
+ # Option examples:
813
+ # has_and_belongs_to_many :projects
814
+ # has_and_belongs_to_many :projects, :include => [ :milestones, :manager ]
815
+ # has_and_belongs_to_many :nations, :class_name => "Country"
816
+ # has_and_belongs_to_many :categories, :join_table => "prods_cats"
817
+ # has_and_belongs_to_many :active_projects, :join_table => 'developers_projects', :delete_sql =>
818
+ # 'DELETE FROM developers_projects WHERE active=1 AND developer_id = #{id} AND project_id = #{record.id}'
819
+ def has_and_belongs_to_many_big_records(association_id, options = {}, &extension)
820
+ reflection = create_has_and_belongs_to_many_big_records_reflection(association_id, options, &extension)
821
+
822
+ collection_accessor_methods(reflection, HasAndBelongsToManyAssociation)
823
+
824
+ # Don't use a before_destroy callback since users' before_destroy
825
+ # callbacks will be executed after the association is wiped out.
826
+ old_method = "destroy_without_habtm_shim_for_#{reflection.name}"
827
+ class_eval <<-end_eval
828
+ alias_method :#{old_method}, :destroy_without_callbacks
829
+ def destroy_without_callbacks
830
+ #{reflection.name}.clear
831
+ #{old_method}
832
+ end
833
+ end_eval
834
+
835
+ add_association_callbacks(reflection.name, options)
836
+
837
+ # deprecated api
838
+ # deprecated_collection_count_method(reflection.name)
839
+ # deprecated_add_association_relation(reflection.name)
840
+ # deprecated_remove_association_relation(reflection.name)
841
+ # deprecated_has_collection_method(reflection.name)
842
+ end
843
+
844
+ alias_method :has_and_belongs_to_many_bigrecords, :has_and_belongs_to_many_big_records
845
+
846
+ private
847
+ def association_accessor_methods_big_record(reflection, association_proxy_class)
848
+ define_method(reflection.name) do |*params|
849
+ force_reload = params.first unless params.empty?
850
+ association = instance_variable_get("@#{reflection.name}")
851
+
852
+ if association.nil? || force_reload
853
+ association = association_proxy_class.new(self, reflection)
854
+ retval = association.reload
855
+ if retval.nil? and association_proxy_class == BelongsToAssociation
856
+ instance_variable_set("@#{reflection.name}", nil)
857
+ return nil
858
+ end
859
+ instance_variable_set("@#{reflection.name}", association)
860
+ end
861
+
862
+ association.target.nil? ? nil : association
863
+ end
864
+
865
+ define_method("#{reflection.name}=") do |new_value|
866
+ association = instance_variable_get("@#{reflection.name}")
867
+ if association.nil?
868
+ association = association_proxy_class.new(self, reflection)
869
+ end
870
+
871
+ association.replace(new_value)
872
+
873
+ unless new_value.nil?
874
+ instance_variable_set("@#{reflection.name}", association)
875
+ else
876
+ instance_variable_set("@#{reflection.name}", nil)
877
+ return nil
878
+ end
879
+
880
+ association
881
+ end
882
+
883
+ define_method("set_#{reflection.name}_target") do |target|
884
+ return if target.nil? and association_proxy_class == BelongsToAssociation
885
+ association = association_proxy_class.new(self, reflection)
886
+ association.target = target
887
+ instance_variable_set("@#{reflection.name}", association)
888
+ end
889
+ end
890
+
891
+ def association_constructor_method_big_record(constructor, reflection, association_proxy_class)
892
+ define_method("#{constructor}_#{reflection.name}") do |*params|
893
+ attributees = params.first unless params.empty?
894
+ replace_existing = params[1].nil? ? true : params[1]
895
+ association = instance_variable_get("@#{reflection.name}")
896
+
897
+ if association.nil?
898
+ association = association_proxy_class.new(self, reflection)
899
+ instance_variable_set("@#{reflection.name}", association)
900
+ end
901
+
902
+ if association_proxy_class == HasOneAssociation
903
+ association.send(constructor, attributees, replace_existing)
904
+ else
905
+ association.send(constructor, attributees)
906
+ end
907
+ end
908
+ end
909
+
910
+ def create_has_many_big_records_reflection(association_id, options, &extension)
911
+ options.assert_valid_keys(
912
+ :class_name, :table_name, :foreign_key,
913
+ :exclusively_dependent, :dependent,
914
+ :select, :conditions, :include, :order, :group, :limit, :offset,
915
+ :as, :through, :source, :source_type,
916
+ :uniq,
917
+ :finder_sql, :counter_sql,
918
+ :before_add, :after_add, :before_remove, :after_remove,
919
+ :extend
920
+ )
921
+
922
+ options[:extend] = create_extension_module(association_id, extension) if block_given?
923
+
924
+ create_reflection_big_record(:has_many_big_records, association_id, options, self)
925
+ end
926
+
927
+ def create_has_one_big_record_reflection(association_id, options)
928
+ options.assert_valid_keys(
929
+ :class_name, :foreign_key, :remote, :conditions, :order, :include, :dependent, :counter_cache, :extend, :as
930
+ )
931
+
932
+ create_reflection_big_record(:has_one_big_record, association_id, options, self)
933
+ end
934
+
935
+ def create_belongs_to_big_record_reflection(association_id, options)
936
+ options.assert_valid_keys(
937
+ :class_name, :foreign_key, :foreign_type, :remote, :conditions, :order, :include, :dependent,
938
+ :counter_cache, :extend, :polymorphic
939
+ )
940
+
941
+ reflection = create_reflection_big_record(:belongs_to_big_record, association_id, options, self)
942
+
943
+ if options[:polymorphic]
944
+ reflection.options[:foreign_type] ||= reflection.class_name.underscore + "_type"
945
+ end
946
+
947
+ reflection
948
+ end
949
+
950
+ def create_belongs_to_many_reflection(association_id, options)
951
+ options.assert_valid_keys(
952
+ :class_name, :foreign_key, :foreign_type, :remote, :conditions, :order, :include, :dependent, :extend, :cache
953
+ )
954
+
955
+ create_reflection_big_record(:belongs_to_many, association_id, options, self)
956
+ end
957
+
958
+ def create_has_and_belongs_to_many_big_records_reflection(association_id, options, &extension)
959
+ options.assert_valid_keys(
960
+ :class_name, :table_name, :join_table, :foreign_key, :association_foreign_key,
961
+ :select, :conditions, :include, :order, :group, :limit, :offset,
962
+ :uniq,
963
+ :finder_sql, :delete_sql, :insert_sql,
964
+ :before_add, :after_add, :before_remove, :after_remove,
965
+ :extend
966
+ )
967
+
968
+ options[:extend] = create_extension_module(association_id, extension) if block_given?
969
+
970
+ reflection = create_reflection_big_record(:has_and_belongs_to_many_big_records, association_id, options, self)
971
+
972
+ reflection.options[:join_table] ||= join_table_name(undecorated_table_name(self.to_s), undecorated_table_name(reflection.class_name))
973
+
974
+ reflection
975
+ end
976
+ end
977
+ end
978
+ end