activerecord 2.3.18 → 3.0.0.beta

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of activerecord might be problematic. Click here for more details.

Files changed (378) hide show
  1. data/CHANGELOG +105 -34
  2. data/examples/performance.rb +3 -39
  3. data/examples/simple.rb +14 -0
  4. data/lib/active_record.rb +81 -47
  5. data/lib/active_record/aggregations.rb +1 -3
  6. data/lib/active_record/association_preload.rb +39 -54
  7. data/lib/active_record/associations.rb +262 -419
  8. data/lib/active_record/associations/association_collection.rb +85 -100
  9. data/lib/active_record/associations/association_proxy.rb +20 -18
  10. data/lib/active_record/associations/belongs_to_association.rb +8 -8
  11. data/lib/active_record/associations/has_and_belongs_to_many_association.rb +13 -35
  12. data/lib/active_record/associations/has_many_association.rb +11 -19
  13. data/lib/active_record/associations/has_many_through_association.rb +30 -183
  14. data/lib/active_record/associations/has_one_association.rb +10 -10
  15. data/lib/active_record/associations/has_one_through_association.rb +13 -11
  16. data/lib/active_record/associations/through_association_scope.rb +153 -0
  17. data/lib/active_record/attribute_methods.rb +17 -370
  18. data/lib/active_record/attribute_methods/before_type_cast.rb +33 -0
  19. data/lib/active_record/attribute_methods/dirty.rb +87 -0
  20. data/lib/active_record/attribute_methods/primary_key.rb +44 -0
  21. data/lib/active_record/attribute_methods/query.rb +37 -0
  22. data/lib/active_record/attribute_methods/read.rb +116 -0
  23. data/lib/active_record/attribute_methods/time_zone_conversion.rb +60 -0
  24. data/lib/active_record/attribute_methods/write.rb +37 -0
  25. data/lib/active_record/autosave_association.rb +20 -41
  26. data/lib/active_record/base.rb +357 -1180
  27. data/lib/active_record/batches.rb +10 -16
  28. data/lib/active_record/callbacks.rb +66 -126
  29. data/lib/active_record/connection_adapters/abstract/connection_pool.rb +17 -13
  30. data/lib/active_record/connection_adapters/abstract/connection_specification.rb +5 -25
  31. data/lib/active_record/connection_adapters/abstract/database_statements.rb +4 -43
  32. data/lib/active_record/connection_adapters/abstract/query_cache.rb +3 -2
  33. data/lib/active_record/connection_adapters/abstract/quoting.rb +15 -4
  34. data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +1 -1
  35. data/lib/active_record/connection_adapters/abstract/schema_statements.rb +18 -72
  36. data/lib/active_record/connection_adapters/abstract_adapter.rb +16 -49
  37. data/lib/active_record/connection_adapters/mysql_adapter.rb +15 -27
  38. data/lib/active_record/connection_adapters/postgresql_adapter.rb +84 -46
  39. data/lib/active_record/connection_adapters/sqlite3_adapter.rb +9 -3
  40. data/lib/active_record/connection_adapters/sqlite_adapter.rb +34 -65
  41. data/lib/active_record/fixtures.rb +21 -25
  42. data/lib/active_record/locale/en.yml +9 -27
  43. data/lib/active_record/locking/optimistic.rb +16 -48
  44. data/lib/active_record/migration.rb +59 -46
  45. data/lib/active_record/named_scope.rb +85 -92
  46. data/lib/active_record/nested_attributes.rb +18 -24
  47. data/lib/active_record/observer.rb +18 -94
  48. data/lib/active_record/railtie.rb +83 -0
  49. data/lib/active_record/railties/controller_runtime.rb +38 -0
  50. data/lib/active_record/railties/databases.rake +477 -0
  51. data/lib/active_record/railties/subscriber.rb +27 -0
  52. data/lib/active_record/reflection.rb +2 -15
  53. data/lib/active_record/relation.rb +339 -0
  54. data/lib/active_record/relation/calculations.rb +259 -0
  55. data/lib/active_record/relation/finder_methods.rb +315 -0
  56. data/lib/active_record/relation/predicate_builder.rb +46 -0
  57. data/lib/active_record/relation/query_methods.rb +218 -0
  58. data/lib/active_record/relation/spawn_methods.rb +102 -0
  59. data/lib/active_record/schema_dumper.rb +10 -6
  60. data/lib/active_record/serialization.rb +31 -74
  61. data/lib/active_record/serializers/xml_serializer.rb +33 -121
  62. data/lib/active_record/session_store.rb +1 -9
  63. data/lib/active_record/test_case.rb +1 -3
  64. data/lib/active_record/timestamp.rb +7 -5
  65. data/lib/active_record/transactions.rb +9 -9
  66. data/lib/active_record/validations.rb +51 -1100
  67. data/lib/active_record/validations/associated.rb +47 -0
  68. data/lib/active_record/validations/uniqueness.rb +181 -0
  69. data/lib/active_record/version.rb +3 -3
  70. data/lib/generators/active_record.rb +30 -0
  71. data/lib/generators/active_record/migration/migration_generator.rb +25 -0
  72. data/lib/generators/active_record/migration/templates/migration.rb +11 -0
  73. data/lib/generators/active_record/model/model_generator.rb +33 -0
  74. data/lib/generators/active_record/model/templates/migration.rb +16 -0
  75. data/lib/generators/active_record/model/templates/model.rb +5 -0
  76. data/lib/generators/active_record/observer/observer_generator.rb +15 -0
  77. data/lib/generators/active_record/observer/templates/observer.rb +2 -0
  78. data/lib/generators/active_record/session_migration/session_migration_generator.rb +24 -0
  79. data/lib/generators/active_record/session_migration/templates/migration.rb +16 -0
  80. metadata +67 -325
  81. data/RUNNING_UNIT_TESTS +0 -36
  82. data/Rakefile +0 -268
  83. data/install.rb +0 -30
  84. data/lib/active_record/calculations.rb +0 -321
  85. data/lib/active_record/connection_adapters/abstract/database_limits.rb +0 -57
  86. data/lib/active_record/dirty.rb +0 -183
  87. data/lib/active_record/serializers/json_serializer.rb +0 -91
  88. data/lib/activerecord.rb +0 -2
  89. data/test/assets/example.log +0 -1
  90. data/test/assets/flowers.jpg +0 -0
  91. data/test/cases/aaa_create_tables_test.rb +0 -24
  92. data/test/cases/active_schema_test_mysql.rb +0 -122
  93. data/test/cases/active_schema_test_postgresql.rb +0 -24
  94. data/test/cases/adapter_test.rb +0 -144
  95. data/test/cases/aggregations_test.rb +0 -167
  96. data/test/cases/ar_schema_test.rb +0 -32
  97. data/test/cases/associations/belongs_to_associations_test.rb +0 -438
  98. data/test/cases/associations/callbacks_test.rb +0 -161
  99. data/test/cases/associations/cascaded_eager_loading_test.rb +0 -131
  100. data/test/cases/associations/eager_load_includes_full_sti_class_test.rb +0 -36
  101. data/test/cases/associations/eager_load_nested_include_test.rb +0 -131
  102. data/test/cases/associations/eager_load_nested_polymorphic_include.rb +0 -19
  103. data/test/cases/associations/eager_singularization_test.rb +0 -145
  104. data/test/cases/associations/eager_test.rb +0 -852
  105. data/test/cases/associations/extension_test.rb +0 -62
  106. data/test/cases/associations/habtm_join_table_test.rb +0 -56
  107. data/test/cases/associations/has_and_belongs_to_many_associations_test.rb +0 -827
  108. data/test/cases/associations/has_many_associations_test.rb +0 -1273
  109. data/test/cases/associations/has_many_through_associations_test.rb +0 -360
  110. data/test/cases/associations/has_one_associations_test.rb +0 -330
  111. data/test/cases/associations/has_one_through_associations_test.rb +0 -209
  112. data/test/cases/associations/inner_join_association_test.rb +0 -93
  113. data/test/cases/associations/inverse_associations_test.rb +0 -566
  114. data/test/cases/associations/join_model_test.rb +0 -712
  115. data/test/cases/associations_test.rb +0 -282
  116. data/test/cases/attribute_methods_test.rb +0 -305
  117. data/test/cases/autosave_association_test.rb +0 -1218
  118. data/test/cases/base_test.rb +0 -2166
  119. data/test/cases/batches_test.rb +0 -81
  120. data/test/cases/binary_test.rb +0 -30
  121. data/test/cases/calculations_test.rb +0 -360
  122. data/test/cases/callbacks_observers_test.rb +0 -38
  123. data/test/cases/callbacks_test.rb +0 -438
  124. data/test/cases/class_inheritable_attributes_test.rb +0 -32
  125. data/test/cases/column_alias_test.rb +0 -17
  126. data/test/cases/column_definition_test.rb +0 -70
  127. data/test/cases/connection_pool_test.rb +0 -25
  128. data/test/cases/connection_test_firebird.rb +0 -8
  129. data/test/cases/connection_test_mysql.rb +0 -65
  130. data/test/cases/copy_table_test_sqlite.rb +0 -80
  131. data/test/cases/counter_cache_test.rb +0 -84
  132. data/test/cases/database_statements_test.rb +0 -12
  133. data/test/cases/datatype_test_postgresql.rb +0 -204
  134. data/test/cases/date_time_test.rb +0 -37
  135. data/test/cases/default_test_firebird.rb +0 -16
  136. data/test/cases/defaults_test.rb +0 -111
  137. data/test/cases/deprecated_finder_test.rb +0 -30
  138. data/test/cases/dirty_test.rb +0 -316
  139. data/test/cases/finder_respond_to_test.rb +0 -76
  140. data/test/cases/finder_test.rb +0 -1098
  141. data/test/cases/fixtures_test.rb +0 -661
  142. data/test/cases/helper.rb +0 -68
  143. data/test/cases/i18n_test.rb +0 -46
  144. data/test/cases/inheritance_test.rb +0 -262
  145. data/test/cases/invalid_date_test.rb +0 -24
  146. data/test/cases/json_serialization_test.rb +0 -219
  147. data/test/cases/lifecycle_test.rb +0 -193
  148. data/test/cases/locking_test.rb +0 -350
  149. data/test/cases/method_scoping_test.rb +0 -704
  150. data/test/cases/migration_test.rb +0 -1649
  151. data/test/cases/migration_test_firebird.rb +0 -124
  152. data/test/cases/mixin_test.rb +0 -96
  153. data/test/cases/modules_test.rb +0 -109
  154. data/test/cases/multiple_db_test.rb +0 -85
  155. data/test/cases/named_scope_test.rb +0 -372
  156. data/test/cases/nested_attributes_test.rb +0 -840
  157. data/test/cases/pk_test.rb +0 -119
  158. data/test/cases/pooled_connections_test.rb +0 -103
  159. data/test/cases/query_cache_test.rb +0 -129
  160. data/test/cases/readonly_test.rb +0 -107
  161. data/test/cases/reflection_test.rb +0 -234
  162. data/test/cases/reload_models_test.rb +0 -22
  163. data/test/cases/repair_helper.rb +0 -50
  164. data/test/cases/reserved_word_test_mysql.rb +0 -176
  165. data/test/cases/sanitize_test.rb +0 -25
  166. data/test/cases/schema_authorization_test_postgresql.rb +0 -75
  167. data/test/cases/schema_dumper_test.rb +0 -211
  168. data/test/cases/schema_test_postgresql.rb +0 -178
  169. data/test/cases/serialization_test.rb +0 -47
  170. data/test/cases/sp_test_mysql.rb +0 -16
  171. data/test/cases/synonym_test_oracle.rb +0 -17
  172. data/test/cases/timestamp_test.rb +0 -75
  173. data/test/cases/transactions_test.rb +0 -543
  174. data/test/cases/unconnected_test.rb +0 -32
  175. data/test/cases/validations_i18n_test.rb +0 -925
  176. data/test/cases/validations_test.rb +0 -1684
  177. data/test/cases/xml_serialization_test.rb +0 -240
  178. data/test/cases/yaml_serialization_test.rb +0 -11
  179. data/test/config.rb +0 -5
  180. data/test/connections/jdbc_jdbcderby/connection.rb +0 -18
  181. data/test/connections/jdbc_jdbch2/connection.rb +0 -18
  182. data/test/connections/jdbc_jdbchsqldb/connection.rb +0 -18
  183. data/test/connections/jdbc_jdbcmysql/connection.rb +0 -26
  184. data/test/connections/jdbc_jdbcpostgresql/connection.rb +0 -26
  185. data/test/connections/jdbc_jdbcsqlite3/connection.rb +0 -25
  186. data/test/connections/native_db2/connection.rb +0 -25
  187. data/test/connections/native_firebird/connection.rb +0 -26
  188. data/test/connections/native_frontbase/connection.rb +0 -27
  189. data/test/connections/native_mysql/connection.rb +0 -25
  190. data/test/connections/native_openbase/connection.rb +0 -21
  191. data/test/connections/native_oracle/connection.rb +0 -27
  192. data/test/connections/native_postgresql/connection.rb +0 -21
  193. data/test/connections/native_sqlite/connection.rb +0 -25
  194. data/test/connections/native_sqlite3/connection.rb +0 -25
  195. data/test/connections/native_sqlite3/in_memory_connection.rb +0 -18
  196. data/test/connections/native_sybase/connection.rb +0 -23
  197. data/test/fixtures/accounts.yml +0 -29
  198. data/test/fixtures/all/developers.yml +0 -0
  199. data/test/fixtures/all/people.csv +0 -0
  200. data/test/fixtures/all/tasks.yml +0 -0
  201. data/test/fixtures/author_addresses.yml +0 -5
  202. data/test/fixtures/author_favorites.yml +0 -4
  203. data/test/fixtures/authors.yml +0 -9
  204. data/test/fixtures/binaries.yml +0 -132
  205. data/test/fixtures/books.yml +0 -7
  206. data/test/fixtures/categories.yml +0 -14
  207. data/test/fixtures/categories/special_categories.yml +0 -9
  208. data/test/fixtures/categories/subsubdir/arbitrary_filename.yml +0 -4
  209. data/test/fixtures/categories_ordered.yml +0 -7
  210. data/test/fixtures/categories_posts.yml +0 -23
  211. data/test/fixtures/categorizations.yml +0 -17
  212. data/test/fixtures/clubs.yml +0 -6
  213. data/test/fixtures/comments.yml +0 -59
  214. data/test/fixtures/companies.yml +0 -56
  215. data/test/fixtures/computers.yml +0 -4
  216. data/test/fixtures/courses.yml +0 -7
  217. data/test/fixtures/customers.yml +0 -26
  218. data/test/fixtures/developers.yml +0 -21
  219. data/test/fixtures/developers_projects.yml +0 -17
  220. data/test/fixtures/edges.yml +0 -6
  221. data/test/fixtures/entrants.yml +0 -14
  222. data/test/fixtures/faces.yml +0 -11
  223. data/test/fixtures/fk_test_has_fk.yml +0 -3
  224. data/test/fixtures/fk_test_has_pk.yml +0 -2
  225. data/test/fixtures/funny_jokes.yml +0 -10
  226. data/test/fixtures/interests.yml +0 -33
  227. data/test/fixtures/items.yml +0 -4
  228. data/test/fixtures/jobs.yml +0 -7
  229. data/test/fixtures/legacy_things.yml +0 -3
  230. data/test/fixtures/mateys.yml +0 -4
  231. data/test/fixtures/member_types.yml +0 -6
  232. data/test/fixtures/members.yml +0 -6
  233. data/test/fixtures/memberships.yml +0 -20
  234. data/test/fixtures/men.yml +0 -5
  235. data/test/fixtures/minimalistics.yml +0 -2
  236. data/test/fixtures/mixed_case_monkeys.yml +0 -6
  237. data/test/fixtures/mixins.yml +0 -29
  238. data/test/fixtures/movies.yml +0 -7
  239. data/test/fixtures/naked/csv/accounts.csv +0 -1
  240. data/test/fixtures/naked/yml/accounts.yml +0 -1
  241. data/test/fixtures/naked/yml/companies.yml +0 -1
  242. data/test/fixtures/naked/yml/courses.yml +0 -1
  243. data/test/fixtures/organizations.yml +0 -5
  244. data/test/fixtures/owners.yml +0 -7
  245. data/test/fixtures/parrots.yml +0 -27
  246. data/test/fixtures/parrots_pirates.yml +0 -7
  247. data/test/fixtures/people.yml +0 -15
  248. data/test/fixtures/pets.yml +0 -14
  249. data/test/fixtures/pirates.yml +0 -9
  250. data/test/fixtures/polymorphic_designs.yml +0 -19
  251. data/test/fixtures/polymorphic_prices.yml +0 -19
  252. data/test/fixtures/posts.yml +0 -52
  253. data/test/fixtures/price_estimates.yml +0 -7
  254. data/test/fixtures/projects.yml +0 -7
  255. data/test/fixtures/readers.yml +0 -9
  256. data/test/fixtures/references.yml +0 -17
  257. data/test/fixtures/reserved_words/distinct.yml +0 -5
  258. data/test/fixtures/reserved_words/distincts_selects.yml +0 -11
  259. data/test/fixtures/reserved_words/group.yml +0 -14
  260. data/test/fixtures/reserved_words/select.yml +0 -8
  261. data/test/fixtures/reserved_words/values.yml +0 -7
  262. data/test/fixtures/ships.yml +0 -5
  263. data/test/fixtures/sponsors.yml +0 -9
  264. data/test/fixtures/subscribers.yml +0 -7
  265. data/test/fixtures/subscriptions.yml +0 -12
  266. data/test/fixtures/taggings.yml +0 -28
  267. data/test/fixtures/tags.yml +0 -7
  268. data/test/fixtures/tasks.yml +0 -7
  269. data/test/fixtures/tees.yml +0 -4
  270. data/test/fixtures/ties.yml +0 -4
  271. data/test/fixtures/topics.yml +0 -42
  272. data/test/fixtures/toys.yml +0 -4
  273. data/test/fixtures/treasures.yml +0 -10
  274. data/test/fixtures/vertices.yml +0 -4
  275. data/test/fixtures/warehouse-things.yml +0 -3
  276. data/test/fixtures/zines.yml +0 -5
  277. data/test/migrations/broken/100_migration_that_raises_exception.rb +0 -10
  278. data/test/migrations/decimal/1_give_me_big_numbers.rb +0 -15
  279. data/test/migrations/duplicate/1_people_have_last_names.rb +0 -9
  280. data/test/migrations/duplicate/2_we_need_reminders.rb +0 -12
  281. data/test/migrations/duplicate/3_foo.rb +0 -7
  282. data/test/migrations/duplicate/3_innocent_jointable.rb +0 -12
  283. data/test/migrations/duplicate_names/20080507052938_chunky.rb +0 -7
  284. data/test/migrations/duplicate_names/20080507053028_chunky.rb +0 -7
  285. data/test/migrations/interleaved/pass_1/3_innocent_jointable.rb +0 -12
  286. data/test/migrations/interleaved/pass_2/1_people_have_last_names.rb +0 -9
  287. data/test/migrations/interleaved/pass_2/3_innocent_jointable.rb +0 -12
  288. data/test/migrations/interleaved/pass_3/1_people_have_last_names.rb +0 -9
  289. data/test/migrations/interleaved/pass_3/2_i_raise_on_down.rb +0 -8
  290. data/test/migrations/interleaved/pass_3/3_innocent_jointable.rb +0 -12
  291. data/test/migrations/missing/1000_people_have_middle_names.rb +0 -9
  292. data/test/migrations/missing/1_people_have_last_names.rb +0 -9
  293. data/test/migrations/missing/3_we_need_reminders.rb +0 -12
  294. data/test/migrations/missing/4_innocent_jointable.rb +0 -12
  295. data/test/migrations/valid/1_people_have_last_names.rb +0 -9
  296. data/test/migrations/valid/2_we_need_reminders.rb +0 -12
  297. data/test/migrations/valid/3_innocent_jointable.rb +0 -12
  298. data/test/models/author.rb +0 -151
  299. data/test/models/auto_id.rb +0 -4
  300. data/test/models/binary.rb +0 -2
  301. data/test/models/bird.rb +0 -9
  302. data/test/models/book.rb +0 -4
  303. data/test/models/categorization.rb +0 -5
  304. data/test/models/category.rb +0 -34
  305. data/test/models/citation.rb +0 -6
  306. data/test/models/club.rb +0 -13
  307. data/test/models/column_name.rb +0 -3
  308. data/test/models/comment.rb +0 -29
  309. data/test/models/company.rb +0 -173
  310. data/test/models/company_in_module.rb +0 -78
  311. data/test/models/computer.rb +0 -3
  312. data/test/models/contact.rb +0 -16
  313. data/test/models/contract.rb +0 -5
  314. data/test/models/course.rb +0 -3
  315. data/test/models/customer.rb +0 -73
  316. data/test/models/default.rb +0 -2
  317. data/test/models/developer.rb +0 -101
  318. data/test/models/edge.rb +0 -5
  319. data/test/models/entrant.rb +0 -3
  320. data/test/models/essay.rb +0 -3
  321. data/test/models/event.rb +0 -3
  322. data/test/models/event_author.rb +0 -8
  323. data/test/models/face.rb +0 -7
  324. data/test/models/guid.rb +0 -2
  325. data/test/models/interest.rb +0 -5
  326. data/test/models/invoice.rb +0 -4
  327. data/test/models/item.rb +0 -7
  328. data/test/models/job.rb +0 -5
  329. data/test/models/joke.rb +0 -3
  330. data/test/models/keyboard.rb +0 -3
  331. data/test/models/legacy_thing.rb +0 -3
  332. data/test/models/line_item.rb +0 -3
  333. data/test/models/man.rb +0 -9
  334. data/test/models/matey.rb +0 -4
  335. data/test/models/member.rb +0 -12
  336. data/test/models/member_detail.rb +0 -5
  337. data/test/models/member_type.rb +0 -3
  338. data/test/models/membership.rb +0 -9
  339. data/test/models/minimalistic.rb +0 -2
  340. data/test/models/mixed_case_monkey.rb +0 -3
  341. data/test/models/movie.rb +0 -5
  342. data/test/models/order.rb +0 -4
  343. data/test/models/organization.rb +0 -6
  344. data/test/models/owner.rb +0 -5
  345. data/test/models/parrot.rb +0 -22
  346. data/test/models/person.rb +0 -16
  347. data/test/models/pet.rb +0 -5
  348. data/test/models/pirate.rb +0 -80
  349. data/test/models/polymorphic_design.rb +0 -3
  350. data/test/models/polymorphic_price.rb +0 -3
  351. data/test/models/post.rb +0 -102
  352. data/test/models/price_estimate.rb +0 -3
  353. data/test/models/project.rb +0 -30
  354. data/test/models/reader.rb +0 -4
  355. data/test/models/reference.rb +0 -4
  356. data/test/models/reply.rb +0 -46
  357. data/test/models/ship.rb +0 -19
  358. data/test/models/ship_part.rb +0 -7
  359. data/test/models/sponsor.rb +0 -4
  360. data/test/models/subject.rb +0 -4
  361. data/test/models/subscriber.rb +0 -8
  362. data/test/models/subscription.rb +0 -4
  363. data/test/models/tag.rb +0 -7
  364. data/test/models/tagging.rb +0 -10
  365. data/test/models/task.rb +0 -3
  366. data/test/models/tee.rb +0 -4
  367. data/test/models/tie.rb +0 -4
  368. data/test/models/topic.rb +0 -80
  369. data/test/models/toy.rb +0 -6
  370. data/test/models/treasure.rb +0 -8
  371. data/test/models/vertex.rb +0 -9
  372. data/test/models/warehouse_thing.rb +0 -5
  373. data/test/models/zine.rb +0 -3
  374. data/test/schema/mysql_specific_schema.rb +0 -31
  375. data/test/schema/postgresql_specific_schema.rb +0 -114
  376. data/test/schema/schema.rb +0 -550
  377. data/test/schema/schema2.rb +0 -6
  378. data/test/schema/sqlite_specific_schema.rb +0 -25
@@ -40,7 +40,7 @@ module ActiveRecord
40
40
  #
41
41
  # The example SqlBypass class is a generic SQL session store. You may
42
42
  # use it as a basis for high-performance database-specific stores.
43
- class SessionStore < ActionController::Session::AbstractStore
43
+ class SessionStore < ActionDispatch::Session::AbstractStore
44
44
  # The default Active Record class.
45
45
  class Session < ActiveRecord::Base
46
46
  ##
@@ -310,14 +310,6 @@ module ActiveRecord
310
310
  return true
311
311
  end
312
312
 
313
- def destroy(env)
314
- if sid = current_session_id(env)
315
- Base.silence do
316
- get_session_model(env, sid).destroy
317
- end
318
- end
319
- end
320
-
321
313
  def get_session_model(env, sid)
322
314
  if env[ENV_SESSION_OPTIONS_KEY][:id].nil?
323
315
  env[SESSION_RECORD_KEY] = find_session(sid)
@@ -1,5 +1,3 @@
1
- require "active_support/test_case"
2
-
3
1
  module ActiveRecord
4
2
  class TestCase < ActiveSupport::TestCase #:nodoc:
5
3
  def assert_date_from_db(expected, actual, message = nil)
@@ -20,7 +18,7 @@ module ActiveRecord
20
18
  patterns_to_match.each do |pattern|
21
19
  failed_patterns << pattern unless $queries_executed.any?{ |sql| pattern === sql }
22
20
  end
23
- assert failed_patterns.empty?, "Query pattern(s) #{failed_patterns.map(&:inspect).join(', ')} not found."
21
+ assert failed_patterns.empty?, "Query pattern(s) #{failed_patterns.map(&:inspect).join(', ')} not found.#{$queries_executed.size == 0 ? '' : "\nQueries:\n#{$queries_executed.join("\n")}"}"
24
22
  end
25
23
 
26
24
  def assert_queries(num = 1)
@@ -8,12 +8,14 @@ module ActiveRecord
8
8
  # Timestamps are in the local timezone by default but you can use UTC by setting
9
9
  # <tt>ActiveRecord::Base.default_timezone = :utc</tt>
10
10
  module Timestamp
11
- def self.included(base) #:nodoc:
12
- base.alias_method_chain :create, :timestamps
13
- base.alias_method_chain :update, :timestamps
11
+ extend ActiveSupport::Concern
14
12
 
15
- base.class_inheritable_accessor :record_timestamps, :instance_writer => false
16
- base.record_timestamps = true
13
+ included do
14
+ alias_method_chain :create, :timestamps
15
+ alias_method_chain :update, :timestamps
16
+
17
+ class_inheritable_accessor :record_timestamps, :instance_writer => false
18
+ self.record_timestamps = true
17
19
  end
18
20
 
19
21
  # Saves the record with the updated_at/on attributes set to the current time.
@@ -3,16 +3,14 @@ require 'thread'
3
3
  module ActiveRecord
4
4
  # See ActiveRecord::Transactions::ClassMethods for documentation.
5
5
  module Transactions
6
+ extend ActiveSupport::Concern
7
+
6
8
  class TransactionError < ActiveRecordError # :nodoc:
7
9
  end
8
10
 
9
- def self.included(base)
10
- base.extend(ClassMethods)
11
-
12
- base.class_eval do
13
- [:destroy, :save, :save!].each do |method|
14
- alias_method_chain method, :transactions
15
- end
11
+ included do
12
+ [:destroy, :save, :save!].each do |method|
13
+ alias_method_chain method, :transactions
16
14
  end
17
15
  end
18
16
 
@@ -175,6 +173,8 @@ module ActiveRecord
175
173
  # end # RELEASE savepoint active_record_1
176
174
  # # ^^^^ BOOM! database error!
177
175
  # end
176
+ #
177
+ # Note that "TRUNCATE" is also a MySQL DDL statement!
178
178
  module ClassMethods
179
179
  # See ActiveRecord::Transactions::ClassMethods for detailed documentation.
180
180
  def transaction(options = {}, &block)
@@ -192,8 +192,8 @@ module ActiveRecord
192
192
  with_transaction_returning_status(:destroy_without_transactions)
193
193
  end
194
194
 
195
- def save_with_transactions(perform_validation = true) #:nodoc:
196
- rollback_active_record_state! { with_transaction_returning_status(:save_without_transactions, perform_validation) }
195
+ def save_with_transactions(*args) #:nodoc:
196
+ rollback_active_record_state! { with_transaction_returning_status(:save_without_transactions, *args) }
197
197
  end
198
198
 
199
199
  def save_with_transactions! #:nodoc:
@@ -10,1055 +10,21 @@ module ActiveRecord
10
10
  attr_reader :record
11
11
  def initialize(record)
12
12
  @record = record
13
- errors = @record.errors.full_messages.join(I18n.t('support.array.words_connector', :default => ', '))
14
- super(I18n.t('activerecord.errors.messages.record_invalid', :errors => errors))
13
+ errors = @record.errors.full_messages.join(", ")
14
+ super(I18n.t("activerecord.errors.messages.record_invalid", :errors => errors))
15
15
  end
16
16
  end
17
17
 
18
- class Error
19
- attr_accessor :base, :attribute, :type, :message, :options
20
-
21
- def initialize(base, attribute, type = nil, options = {})
22
- self.base = base
23
- self.attribute = attribute
24
- self.type = type || :invalid
25
- self.options = options
26
- self.message = options.delete(:message) || self.type
27
- end
28
-
29
- def message
30
- # When type is a string, it means that we do not have to do a lookup, because
31
- # the user already sent the "final" message.
32
- type.is_a?(String) ? type : generate_message(default_options)
33
- end
34
-
35
- def full_message
36
- attribute.to_s == 'base' ? message : generate_full_message(default_options)
37
- end
38
-
39
- alias :to_s :message
40
-
41
- def value
42
- @base.respond_to?(attribute) ? @base.send(attribute) : nil
43
- end
44
-
45
- protected
46
-
47
- # Translates an error message in it's default scope (<tt>activerecord.errrors.messages</tt>).
48
- # Error messages are first looked up in <tt>models.MODEL.attributes.ATTRIBUTE.MESSAGE</tt>, if it's not there,
49
- # it's looked up in <tt>models.MODEL.MESSAGE</tt> and if that is not there it returns the translation of the
50
- # default message (e.g. <tt>activerecord.errors.messages.MESSAGE</tt>). The translated model name,
51
- # translated attribute name and the value are available for interpolation.
52
- #
53
- # When using inheritence in your models, it will check all the inherited models too, but only if the model itself
54
- # hasn't been found. Say you have <tt>class Admin < User; end</tt> and you wanted the translation for the <tt>:blank</tt>
55
- # error +message+ for the <tt>title</tt> +attribute+, it looks for these translations:
56
- #
57
- # <ol>
58
- # <li><tt>activerecord.errors.models.admin.attributes.title.blank</tt></li>
59
- # <li><tt>activerecord.errors.models.admin.blank</tt></li>
60
- # <li><tt>activerecord.errors.models.user.attributes.title.blank</tt></li>
61
- # <li><tt>activerecord.errors.models.user.blank</tt></li>
62
- # <li><tt>activerecord.errors.messages.blank</tt></li>
63
- # <li>any default you provided through the +options+ hash (in the activerecord.errors scope)</li>
64
- # </ol>
65
- def generate_message(options = {})
66
- keys = @base.class.self_and_descendants_from_active_record.map do |klass|
67
- [ :"models.#{klass.name.underscore}.attributes.#{attribute}.#{@message}",
68
- :"models.#{klass.name.underscore}.#{@message}" ]
69
- end.flatten
70
-
71
- keys << options.delete(:default)
72
- keys << :"messages.#{@message}"
73
- keys << @message if @message.is_a?(String)
74
- keys << @type unless @type == @message
75
- keys.compact!
76
-
77
- options.merge!(:default => keys)
78
- I18n.translate(keys.shift, options)
79
- end
80
-
81
- # Wraps an error message into a full_message format.
82
- #
83
- # The default full_message format for any locale is <tt>"%{attribute} %{message}"</tt>.
84
- # One can specify locale specific default full_message format by storing it as a
85
- # translation for the key <tt>:"activerecord.errors.full_messages.format"</tt>.
86
- #
87
- # Additionally one can specify a validation specific error message format by
88
- # storing a translation for <tt>:"activerecord.errors.full_messages.[message_key]"</tt>.
89
- # E.g. the full_message format for any validation that uses :blank as a message
90
- # key (such as validates_presence_of) can be stored to <tt>:"activerecord.errors.full_messages.blank".</tt>
91
- #
92
- # Because the message key used by a validation can be overwritten on the
93
- # <tt>validates_*</tt> class macro level one can customize the full_message format for
94
- # any particular validation:
95
- #
96
- # # app/models/article.rb
97
- # class Article < ActiveRecord::Base
98
- # validates_presence_of :title, :message => :"title.blank"
99
- # end
100
- #
101
- # # config/locales/en.yml
102
- # en:
103
- # activerecord:
104
- # errors:
105
- # full_messages:
106
- # title:
107
- # blank: This title is screwed!
108
- def generate_full_message(options = {})
109
- keys = [
110
- :"full_messages.#{@message}",
111
- :'full_messages.format',
112
- '%{attribute} %{message}'
113
- ]
114
-
115
- options.merge!(:default => keys, :message => self.message)
116
- I18n.translate(keys.shift, options)
117
- end
118
-
119
- # Return user options with default options.
120
- #
121
- def default_options
122
- options.reverse_merge :scope => [:activerecord, :errors],
123
- :model => @base.class.human_name,
124
- :attribute => @base.class.human_attribute_name(attribute.to_s),
125
- :value => value
126
- end
127
- end
128
-
129
- # Active Record validation is reported to and from this object, which is used by Base#save to
130
- # determine whether the object is in a valid state to be saved. See usage example in Validations.
131
- class Errors
132
- include Enumerable
133
-
134
- class << self
135
- def default_error_messages
136
- ActiveSupport::Deprecation.warn("ActiveRecord::Errors.default_error_messages has been deprecated. Please use I18n.translate('activerecord.errors.messages').")
137
- I18n.translate 'activerecord.errors.messages'
138
- end
139
- end
140
-
141
- def initialize(base) # :nodoc:
142
- @base = base
143
- clear
144
- end
145
-
146
- # Adds an error to the base object instead of any particular attribute. This is used
147
- # to report errors that don't tie to any specific attribute, but rather to the object
148
- # as a whole. These error messages don't get prepended with any field name when iterating
149
- # with +each_full+, so they should be complete sentences.
150
- def add_to_base(msg)
151
- add(:base, msg)
152
- end
153
-
154
- # Adds an error message (+messsage+) to the +attribute+, which will be returned on a call to <tt>on(attribute)</tt>
155
- # for the same attribute and ensure that this error object returns false when asked if <tt>empty?</tt>. More than one
156
- # error can be added to the same +attribute+ in which case an array will be returned on a call to <tt>on(attribute)</tt>.
157
- # If no +messsage+ is supplied, :invalid is assumed.
158
- # If +message+ is a Symbol, it will be translated, using the appropriate scope (see translate_error).
159
- #
160
- def add(attribute, message = nil, options = {})
161
- options[:message] = options.delete(:default) if options[:default].is_a?(Symbol)
162
- error, message = message, nil if message.is_a?(Error)
163
-
164
- @errors[attribute.to_s] ||= []
165
- @errors[attribute.to_s] << (error || Error.new(@base, attribute, message, options))
166
- end
167
-
168
- # Will add an error message to each of the attributes in +attributes+ that is empty.
169
- def add_on_empty(attributes, custom_message = nil)
170
- for attr in [attributes].flatten
171
- value = @base.respond_to?(attr.to_s) ? @base.send(attr.to_s) : @base[attr.to_s]
172
- is_empty = value.respond_to?(:empty?) ? value.empty? : false
173
- add(attr, :empty, :default => custom_message) unless !value.nil? && !is_empty
174
- end
175
- end
176
-
177
- # Will add an error message to each of the attributes in +attributes+ that is blank (using Object#blank?).
178
- def add_on_blank(attributes, custom_message = nil)
179
- for attr in [attributes].flatten
180
- value = @base.respond_to?(attr.to_s) ? @base.send(attr.to_s) : @base[attr.to_s]
181
- add(attr, :blank, :default => custom_message) if value.blank?
182
- end
183
- end
184
-
185
- # Returns true if the specified +attribute+ has errors associated with it.
186
- #
187
- # class Company < ActiveRecord::Base
188
- # validates_presence_of :name, :address, :email
189
- # validates_length_of :name, :in => 5..30
190
- # end
191
- #
192
- # company = Company.create(:address => '123 First St.')
193
- # company.errors.invalid?(:name) # => true
194
- # company.errors.invalid?(:address) # => false
195
- def invalid?(attribute)
196
- !@errors[attribute.to_s].nil?
197
- end
198
-
199
- # Returns +nil+, if no errors are associated with the specified +attribute+.
200
- # Returns the error message, if one error is associated with the specified +attribute+.
201
- # Returns an array of error messages, if more than one error is associated with the specified +attribute+.
202
- #
203
- # class Company < ActiveRecord::Base
204
- # validates_presence_of :name, :address, :email
205
- # validates_length_of :name, :in => 5..30
206
- # end
207
- #
208
- # company = Company.create(:address => '123 First St.')
209
- # company.errors.on(:name) # => ["is too short (minimum is 5 characters)", "can't be blank"]
210
- # company.errors.on(:email) # => "can't be blank"
211
- # company.errors.on(:address) # => nil
212
- def on(attribute)
213
- attribute = attribute.to_s
214
- return nil unless @errors.has_key?(attribute)
215
- errors = @errors[attribute].map(&:to_s)
216
- errors.size == 1 ? errors.first : errors
217
- end
218
-
219
- alias :[] :on
220
-
221
- # Returns errors assigned to the base object through +add_to_base+ according to the normal rules of <tt>on(attribute)</tt>.
222
- def on_base
223
- on(:base)
224
- end
225
-
226
- # Yields each attribute and associated message per error added.
227
- #
228
- # class Company < ActiveRecord::Base
229
- # validates_presence_of :name, :address, :email
230
- # validates_length_of :name, :in => 5..30
231
- # end
232
- #
233
- # company = Company.create(:address => '123 First St.')
234
- # company.errors.each{|attr,msg| puts "#{attr} - #{msg}" }
235
- # # => name - is too short (minimum is 5 characters)
236
- # # name - can't be blank
237
- # # address - can't be blank
238
- def each
239
- @errors.each_key { |attr| @errors[attr].each { |error| yield attr, error.message } }
240
- end
241
-
242
- # Yields each attribute and associated error per error added.
243
- #
244
- # class Company < ActiveRecord::Base
245
- # validates_presence_of :name, :address, :email
246
- # validates_length_of :name, :in => 5..30
247
- # end
248
- #
249
- # company = Company.create(:address => '123 First St.')
250
- # company.errors.each_error{|attr,err| puts "#{attr} - #{err.type}" }
251
- # # => name - :too_short
252
- # # name - :blank
253
- # # address - :blank
254
- def each_error
255
- @errors.each_key { |attr| @errors[attr].each { |error| yield attr, error } }
256
- end
257
-
258
- # Yields each full error message added. So <tt>Person.errors.add("first_name", "can't be empty")</tt> will be returned
259
- # through iteration as "First name can't be empty".
260
- #
261
- # class Company < ActiveRecord::Base
262
- # validates_presence_of :name, :address, :email
263
- # validates_length_of :name, :in => 5..30
264
- # end
265
- #
266
- # company = Company.create(:address => '123 First St.')
267
- # company.errors.each_full{|msg| puts msg }
268
- # # => Name is too short (minimum is 5 characters)
269
- # # Name can't be blank
270
- # # Address can't be blank
271
- def each_full
272
- full_messages.each { |msg| yield msg }
273
- end
274
-
275
- # Returns all the full error messages in an array.
276
- #
277
- # class Company < ActiveRecord::Base
278
- # validates_presence_of :name, :address, :email
279
- # validates_length_of :name, :in => 5..30
280
- # end
281
- #
282
- # company = Company.create(:address => '123 First St.')
283
- # company.errors.full_messages # =>
284
- # ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Address can't be blank"]
285
- def full_messages(options = {})
286
- @errors.values.inject([]) do |full_messages, errors|
287
- full_messages + errors.map { |error| error.full_message }
288
- end
289
- end
290
-
291
- # Returns true if no errors have been added.
292
- def empty?
293
- @errors.empty?
294
- end
295
-
296
- # Removes all errors that have been added.
297
- def clear
298
- @errors = ActiveSupport::OrderedHash.new
299
- end
300
-
301
- # Returns the total number of errors added. Two errors added to the same attribute will be counted as such.
302
- def size
303
- @errors.values.inject(0) { |error_count, attribute| error_count + attribute.size }
304
- end
305
-
306
- alias_method :count, :size
307
- alias_method :length, :size
308
-
309
- # Returns an XML representation of this error object.
310
- #
311
- # class Company < ActiveRecord::Base
312
- # validates_presence_of :name, :address, :email
313
- # validates_length_of :name, :in => 5..30
314
- # end
315
- #
316
- # company = Company.create(:address => '123 First St.')
317
- # company.errors.to_xml
318
- # # => <?xml version="1.0" encoding="UTF-8"?>
319
- # # <errors>
320
- # # <error>Name is too short (minimum is 5 characters)</error>
321
- # # <error>Name can't be blank</error>
322
- # # <error>Address can't be blank</error>
323
- # # </errors>
324
- def to_xml(options={})
325
- options[:root] ||= "errors"
326
- options[:indent] ||= 2
327
- options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])
328
-
329
- options[:builder].instruct! unless options.delete(:skip_instruct)
330
- options[:builder].errors do |e|
331
- full_messages.each { |msg| e.error(msg) }
332
- end
333
- end
334
-
335
- def generate_message(attribute, message = :invalid, options = {})
336
- Error.new(@base, attribute, message, options).to_s
337
- end
338
- end
339
-
340
-
341
- # Please do have a look at ActiveRecord::Validations::ClassMethods for a higher level of validations.
342
- #
343
- # Active Records implement validation by overwriting Base#validate (or the variations, +validate_on_create+ and
344
- # +validate_on_update+). Each of these methods can inspect the state of the object, which usually means ensuring
345
- # that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression).
346
- #
347
- # Example:
348
- #
349
- # class Person < ActiveRecord::Base
350
- # protected
351
- # def validate
352
- # errors.add_on_empty %w( first_name last_name )
353
- # errors.add("phone_number", "has invalid format") unless phone_number =~ /[0-9]*/
354
- # end
355
- #
356
- # def validate_on_create # is only run the first time a new object is saved
357
- # unless valid_discount?(membership_discount)
358
- # errors.add("membership_discount", "has expired")
359
- # end
360
- # end
361
- #
362
- # def validate_on_update
363
- # errors.add_to_base("No changes have occurred") if unchanged_attributes?
364
- # end
365
- # end
366
- #
367
- # person = Person.new("first_name" => "David", "phone_number" => "what?")
368
- # person.save # => false (and doesn't do the save)
369
- # person.errors.empty? # => false
370
- # person.errors.count # => 2
371
- # person.errors.on "last_name" # => "can't be empty"
372
- # person.errors.on "phone_number" # => "has invalid format"
373
- # person.errors.each_full { |msg| puts msg }
374
- # # => "Last name can't be empty\n" +
375
- # # "Phone number has invalid format"
376
- #
377
- # person.attributes = { "last_name" => "Heinemeier", "phone_number" => "555-555" }
378
- # person.save # => true (and person is now saved in the database)
379
- #
380
- # An Errors object is automatically created for every Active Record.
381
18
  module Validations
382
- VALIDATIONS = %w( validate validate_on_create validate_on_update )
19
+ extend ActiveSupport::Concern
20
+ include ActiveModel::Validations
383
21
 
384
- def self.included(base) # :nodoc:
385
- base.extend ClassMethods
386
- base.class_eval do
387
- alias_method_chain :save, :validation
388
- alias_method_chain :save!, :validation
389
- end
390
-
391
- base.send :include, ActiveSupport::Callbacks
392
- base.define_callbacks *VALIDATIONS
22
+ included do
23
+ alias_method_chain :save, :validation
24
+ alias_method_chain :save!, :validation
393
25
  end
394
26
 
395
- # Active Record classes can implement validations in several ways. The highest level, easiest to read,
396
- # and recommended approach is to use the declarative <tt>validates_..._of</tt> class methods (and
397
- # +validates_associated+) documented below. These are sufficient for most model validations.
398
- #
399
- # Slightly lower level is +validates_each+. It provides some of the same options as the purely declarative
400
- # validation methods, but like all the lower-level approaches it requires manually adding to the errors collection
401
- # when the record is invalid.
402
- #
403
- # At a yet lower level, a model can use the class methods +validate+, +validate_on_create+ and +validate_on_update+
404
- # to add validation methods or blocks. These are ActiveSupport::Callbacks and follow the same rules of inheritance
405
- # and chaining.
406
- #
407
- # The lowest level style is to define the instance methods +validate+, +validate_on_create+ and +validate_on_update+
408
- # as documented in ActiveRecord::Validations.
409
- #
410
- # == +validate+, +validate_on_create+ and +validate_on_update+ Class Methods
411
- #
412
- # Calls to these methods add a validation method or block to the class. Again, this approach is recommended
413
- # only when the higher-level methods documented below (<tt>validates_..._of</tt> and +validates_associated+) are
414
- # insufficient to handle the required validation.
415
- #
416
- # This can be done with a symbol pointing to a method:
417
- #
418
- # class Comment < ActiveRecord::Base
419
- # validate :must_be_friends
420
- #
421
- # def must_be_friends
422
- # errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
423
- # end
424
- # end
425
- #
426
- # Or with a block which is passed the current record to be validated:
427
- #
428
- # class Comment < ActiveRecord::Base
429
- # validate do |comment|
430
- # comment.must_be_friends
431
- # end
432
- #
433
- # def must_be_friends
434
- # errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
435
- # end
436
- # end
437
- #
438
- # This usage applies to +validate_on_create+ and +validate_on_update+ as well.
439
27
  module ClassMethods
440
- DEFAULT_VALIDATION_OPTIONS = {
441
- :on => :save,
442
- :allow_nil => false,
443
- :allow_blank => false,
444
- :message => nil
445
- }.freeze
446
-
447
- ALL_RANGE_OPTIONS = [ :is, :within, :in, :minimum, :maximum ].freeze
448
- ALL_NUMERICALITY_CHECKS = { :greater_than => '>', :greater_than_or_equal_to => '>=',
449
- :equal_to => '==', :less_than => '<', :less_than_or_equal_to => '<=',
450
- :odd => 'odd?', :even => 'even?' }.freeze
451
-
452
- # Validates each attribute against a block.
453
- #
454
- # class Person < ActiveRecord::Base
455
- # validates_each :first_name, :last_name do |record, attr, value|
456
- # record.errors.add attr, 'starts with z.' if value[0] == ?z
457
- # end
458
- # end
459
- #
460
- # Options:
461
- # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
462
- # * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
463
- # * <tt>:allow_blank</tt> - Skip validation if attribute is blank.
464
- # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
465
- # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
466
- # method, proc or string should return or evaluate to a true or false value.
467
- # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
468
- # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
469
- # method, proc or string should return or evaluate to a true or false value.
470
- def validates_each(*attrs)
471
- options = attrs.extract_options!.symbolize_keys
472
- attrs = attrs.flatten
473
-
474
- # Declare the validation.
475
- send(validation_method(options[:on] || :save), options) do |record|
476
- attrs.each do |attr|
477
- value = record.send(attr)
478
- next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank])
479
- yield record, attr, value
480
- end
481
- end
482
- end
483
-
484
- # Encapsulates the pattern of wanting to validate a password or email address field with a confirmation. Example:
485
- #
486
- # Model:
487
- # class Person < ActiveRecord::Base
488
- # validates_confirmation_of :user_name, :password
489
- # validates_confirmation_of :email_address, :message => "should match confirmation"
490
- # end
491
- #
492
- # View:
493
- # <%= password_field "person", "password" %>
494
- # <%= password_field "person", "password_confirmation" %>
495
- #
496
- # The added +password_confirmation+ attribute is virtual; it exists only as an in-memory attribute for validating the password.
497
- # To achieve this, the validation adds accessors to the model for the confirmation attribute. NOTE: This check is performed
498
- # only if +password_confirmation+ is not +nil+, and by default only on save. To require confirmation, make sure to add a presence
499
- # check for the confirmation attribute:
500
- #
501
- # validates_presence_of :password_confirmation, :if => :password_changed?
502
- #
503
- # Configuration options:
504
- # * <tt>:message</tt> - A custom error message (default is: "doesn't match confirmation").
505
- # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
506
- # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
507
- # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
508
- # method, proc or string should return or evaluate to a true or false value.
509
- # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
510
- # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
511
- # method, proc or string should return or evaluate to a true or false value.
512
- def validates_confirmation_of(*attr_names)
513
- configuration = { :on => :save }
514
- configuration.update(attr_names.extract_options!)
515
-
516
- attr_accessor(*(attr_names.map { |n| "#{n}_confirmation" }))
517
-
518
- validates_each(attr_names, configuration) do |record, attr_name, value|
519
- unless record.send("#{attr_name}_confirmation").nil? or value == record.send("#{attr_name}_confirmation")
520
- record.errors.add(attr_name, :confirmation, :default => configuration[:message])
521
- end
522
- end
523
- end
524
-
525
- # Encapsulates the pattern of wanting to validate the acceptance of a terms of service check box (or similar agreement). Example:
526
- #
527
- # class Person < ActiveRecord::Base
528
- # validates_acceptance_of :terms_of_service
529
- # validates_acceptance_of :eula, :message => "must be abided"
530
- # end
531
- #
532
- # If the database column does not exist, the +terms_of_service+ attribute is entirely virtual. This check is
533
- # performed only if +terms_of_service+ is not +nil+ and by default on save.
534
- #
535
- # Configuration options:
536
- # * <tt>:message</tt> - A custom error message (default is: "must be accepted").
537
- # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
538
- # * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default is true).
539
- # * <tt>:accept</tt> - Specifies value that is considered accepted. The default value is a string "1", which
540
- # makes it easy to relate to an HTML checkbox. This should be set to +true+ if you are validating a database
541
- # column, since the attribute is typecast from "1" to +true+ before validation.
542
- # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
543
- # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
544
- # method, proc or string should return or evaluate to a true or false value.
545
- # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
546
- # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
547
- # method, proc or string should return or evaluate to a true or false value.
548
- def validates_acceptance_of(*attr_names)
549
- configuration = { :on => :save, :allow_nil => true, :accept => "1" }
550
- configuration.update(attr_names.extract_options!)
551
-
552
- db_cols = begin
553
- column_names
554
- rescue Exception # To ignore both statement and connection errors
555
- []
556
- end
557
- names = attr_names.reject { |name| db_cols.include?(name.to_s) }
558
- attr_accessor(*names)
559
-
560
- validates_each(attr_names,configuration) do |record, attr_name, value|
561
- unless value == configuration[:accept]
562
- record.errors.add(attr_name, :accepted, :default => configuration[:message])
563
- end
564
- end
565
- end
566
-
567
- # Validates that the specified attributes are not blank (as defined by Object#blank?). Happens by default on save. Example:
568
- #
569
- # class Person < ActiveRecord::Base
570
- # validates_presence_of :first_name
571
- # end
572
- #
573
- # The first_name attribute must be in the object and it cannot be blank.
574
- #
575
- # If you want to validate the presence of a boolean field (where the real values are true and false),
576
- # you will want to use <tt>validates_inclusion_of :field_name, :in => [true, false]</tt>.
577
- #
578
- # This is due to the way Object#blank? handles boolean values: <tt>false.blank? # => true</tt>.
579
- #
580
- # Configuration options:
581
- # * <tt>message</tt> - A custom error message (default is: "can't be blank").
582
- # * <tt>on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>,
583
- # <tt>:update</tt>).
584
- # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
585
- # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).
586
- # The method, proc or string should return or evaluate to a true or false value.
587
- # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
588
- # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).
589
- # The method, proc or string should return or evaluate to a true or false value.
590
- #
591
- def validates_presence_of(*attr_names)
592
- configuration = { :on => :save }
593
- configuration.update(attr_names.extract_options!)
594
-
595
- # can't use validates_each here, because it cannot cope with nonexistent attributes,
596
- # while errors.add_on_empty can
597
- send(validation_method(configuration[:on]), configuration) do |record|
598
- record.errors.add_on_blank(attr_names, configuration[:message])
599
- end
600
- end
601
-
602
- # Validates that the specified attribute matches the length restrictions supplied. Only one option can be used at a time:
603
- #
604
- # class Person < ActiveRecord::Base
605
- # validates_length_of :first_name, :maximum => 30
606
- # validates_length_of :last_name, :maximum => 30, :message => "less than %{count} if you don't mind"
607
- # validates_length_of :fax, :in => 7..32, :allow_nil => true
608
- # validates_length_of :phone, :in => 7..32, :allow_blank => true
609
- # validates_length_of :user_name, :within => 6..20, :too_long => "pick a shorter name", :too_short => "pick a longer name"
610
- # validates_length_of :zip_code, :minimum => 5, :too_short => "please enter at least %{count} characters"
611
- # validates_length_of :smurf_leader, :is => 4, :message => "papa is spelled with %{count} characters... don't play me"
612
- # validates_length_of :essay, :minimum => 100, :too_short => "Your essay must be at least %{count} words"), :tokenizer => lambda {|str| str.scan(/\w+/) }
613
- # end
614
- #
615
- # Configuration options:
616
- # * <tt>:minimum</tt> - The minimum size of the attribute.
617
- # * <tt>:maximum</tt> - The maximum size of the attribute.
618
- # * <tt>:is</tt> - The exact size of the attribute.
619
- # * <tt>:within</tt> - A range specifying the minimum and maximum size of the attribute.
620
- # * <tt>:in</tt> - A synonym(or alias) for <tt>:within</tt>.
621
- # * <tt>:allow_nil</tt> - Attribute may be +nil+; skip validation.
622
- # * <tt>:allow_blank</tt> - Attribute may be blank; skip validation.
623
- # * <tt>:too_long</tt> - The error message if the attribute goes over the maximum (default is: "is too long (maximum is %{count} characters)").
624
- # * <tt>:too_short</tt> - The error message if the attribute goes under the minimum (default is: "is too short (min is %{count} characters)").
625
- # * <tt>:wrong_length</tt> - The error message if using the <tt>:is</tt> method and the attribute is the wrong size (default is: "is the wrong length (should be %{count} characters)").
626
- # * <tt>:message</tt> - The error message to use for a <tt>:minimum</tt>, <tt>:maximum</tt>, or <tt>:is</tt> violation. An alias of the appropriate <tt>too_long</tt>/<tt>too_short</tt>/<tt>wrong_length</tt> message.
627
- # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
628
- # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
629
- # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
630
- # method, proc or string should return or evaluate to a true or false value.
631
- # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
632
- # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
633
- # method, proc or string should return or evaluate to a true or false value.
634
- # * <tt>:tokenizer</tt> - Specifies how to split up the attribute string. (e.g. <tt>:tokenizer => lambda {|str| str.scan(/\w+/)}</tt> to
635
- # count words as in above example.)
636
- # Defaults to <tt>lambda{ |value| value.split(//) }</tt> which counts individual characters.
637
- def validates_length_of(*attrs)
638
- # Merge given options with defaults.
639
- options = {
640
- :tokenizer => lambda {|value| value.split(//)}
641
- }.merge(DEFAULT_VALIDATION_OPTIONS)
642
- options.update(attrs.extract_options!.symbolize_keys)
643
-
644
- # Ensure that one and only one range option is specified.
645
- range_options = ALL_RANGE_OPTIONS & options.keys
646
- case range_options.size
647
- when 0
648
- raise ArgumentError, 'Range unspecified. Specify the :within, :maximum, :minimum, or :is option.'
649
- when 1
650
- # Valid number of options; do nothing.
651
- else
652
- raise ArgumentError, 'Too many range options specified. Choose only one.'
653
- end
654
-
655
- # Get range option and value.
656
- option = range_options.first
657
- option_value = options[range_options.first]
658
- key = {:is => :wrong_length, :minimum => :too_short, :maximum => :too_long}[option]
659
- custom_message = options[:message] || options[key]
660
-
661
- case option
662
- when :within, :in
663
- raise ArgumentError, ":#{option} must be a Range" unless option_value.is_a?(Range)
664
-
665
- validates_each(attrs, options) do |record, attr, value|
666
- value = options[:tokenizer].call(value) if value.kind_of?(String)
667
- if value.nil? or value.size < option_value.begin
668
- record.errors.add(attr, :too_short, :default => custom_message || options[:too_short], :count => option_value.begin)
669
- elsif value.size > option_value.end
670
- record.errors.add(attr, :too_long, :default => custom_message || options[:too_long], :count => option_value.end)
671
- end
672
- end
673
- when :is, :minimum, :maximum
674
- raise ArgumentError, ":#{option} must be a nonnegative Integer" unless option_value.is_a?(Integer) and option_value >= 0
675
-
676
- # Declare different validations per option.
677
- validity_checks = { :is => "==", :minimum => ">=", :maximum => "<=" }
678
-
679
- validates_each(attrs, options) do |record, attr, value|
680
- value = options[:tokenizer].call(value) if value.kind_of?(String)
681
- unless !value.nil? and value.size.method(validity_checks[option])[option_value]
682
- record.errors.add(attr, key, :default => custom_message, :count => option_value)
683
- end
684
- end
685
- end
686
- end
687
-
688
- alias_method :validates_size_of, :validates_length_of
689
-
690
-
691
- # Validates whether the value of the specified attributes are unique across the system. Useful for making sure that only one user
692
- # can be named "davidhh".
693
- #
694
- # class Person < ActiveRecord::Base
695
- # validates_uniqueness_of :user_name, :scope => :account_id
696
- # end
697
- #
698
- # It can also validate whether the value of the specified attributes are unique based on multiple scope parameters. For example,
699
- # making sure that a teacher can only be on the schedule once per semester for a particular class.
700
- #
701
- # class TeacherSchedule < ActiveRecord::Base
702
- # validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
703
- # end
704
- #
705
- # When the record is created, a check is performed to make sure that no record exists in the database with the given value for the specified
706
- # attribute (that maps to a column). When the record is updated, the same check is made but disregarding the record itself.
707
- #
708
- # Configuration options:
709
- # * <tt>:message</tt> - Specifies a custom error message (default is: "has already been taken").
710
- # * <tt>:scope</tt> - One or more columns by which to limit the scope of the uniqueness constraint.
711
- # * <tt>:case_sensitive</tt> - Looks for an exact match. Ignored by non-text columns (+true+ by default).
712
- # * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
713
- # * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
714
- # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
715
- # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
716
- # method, proc or string should return or evaluate to a true or false value.
717
- # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
718
- # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
719
- # method, proc or string should return or evaluate to a true or false value.
720
- #
721
- # === Concurrency and integrity
722
- #
723
- # Using this validation method in conjunction with ActiveRecord::Base#save
724
- # does not guarantee the absence of duplicate record insertions, because
725
- # uniqueness checks on the application level are inherently prone to race
726
- # conditions. For example, suppose that two users try to post a Comment at
727
- # the same time, and a Comment's title must be unique. At the database-level,
728
- # the actions performed by these users could be interleaved in the following manner:
729
- #
730
- # User 1 | User 2
731
- # ------------------------------------+--------------------------------------
732
- # # User 1 checks whether there's |
733
- # # already a comment with the title |
734
- # # 'My Post'. This is not the case. |
735
- # SELECT * FROM comments |
736
- # WHERE title = 'My Post' |
737
- # |
738
- # | # User 2 does the same thing and also
739
- # | # infers that his title is unique.
740
- # | SELECT * FROM comments
741
- # | WHERE title = 'My Post'
742
- # |
743
- # # User 1 inserts his comment. |
744
- # INSERT INTO comments |
745
- # (title, content) VALUES |
746
- # ('My Post', 'hi!') |
747
- # |
748
- # | # User 2 does the same thing.
749
- # | INSERT INTO comments
750
- # | (title, content) VALUES
751
- # | ('My Post', 'hello!')
752
- # |
753
- # | # ^^^^^^
754
- # | # Boom! We now have a duplicate
755
- # | # title!
756
- #
757
- # This could even happen if you use transactions with the 'serializable'
758
- # isolation level. There are several ways to get around this problem:
759
- # - By locking the database table before validating, and unlocking it after
760
- # saving. However, table locking is very expensive, and thus not
761
- # recommended.
762
- # - By locking a lock file before validating, and unlocking it after saving.
763
- # This does not work if you've scaled your Rails application across
764
- # multiple web servers (because they cannot share lock files, or cannot
765
- # do that efficiently), and thus not recommended.
766
- # - Creating a unique index on the field, by using
767
- # ActiveRecord::ConnectionAdapters::SchemaStatements#add_index. In the
768
- # rare case that a race condition occurs, the database will guarantee
769
- # the field's uniqueness.
770
- #
771
- # When the database catches such a duplicate insertion,
772
- # ActiveRecord::Base#save will raise an ActiveRecord::StatementInvalid
773
- # exception. You can either choose to let this error propagate (which
774
- # will result in the default Rails exception page being shown), or you
775
- # can catch it and restart the transaction (e.g. by telling the user
776
- # that the title already exists, and asking him to re-enter the title).
777
- # This technique is also known as optimistic concurrency control:
778
- # http://en.wikipedia.org/wiki/Optimistic_concurrency_control
779
- #
780
- # Active Record currently provides no way to distinguish unique
781
- # index constraint errors from other types of database errors, so you
782
- # will have to parse the (database-specific) exception message to detect
783
- # such a case.
784
- def validates_uniqueness_of(*attr_names)
785
- configuration = { :case_sensitive => true }
786
- configuration.update(attr_names.extract_options!)
787
-
788
- validates_each(attr_names,configuration) do |record, attr_name, value|
789
- # The check for an existing value should be run from a class that
790
- # isn't abstract. This means working down from the current class
791
- # (self), to the first non-abstract class. Since classes don't know
792
- # their subclasses, we have to build the hierarchy between self and
793
- # the record's class.
794
- class_hierarchy = [record.class]
795
- while class_hierarchy.first != self
796
- class_hierarchy.insert(0, class_hierarchy.first.superclass)
797
- end
798
-
799
- # Now we can work our way down the tree to the first non-abstract
800
- # class (which has a database table to query from).
801
- finder_class = class_hierarchy.detect { |klass| !klass.abstract_class? }
802
-
803
- column = finder_class.columns_hash[attr_name.to_s]
804
-
805
- if value.nil?
806
- comparison_operator = "IS ?"
807
- elsif column.text?
808
- comparison_operator = "#{connection.case_sensitive_equality_operator} ?"
809
- value = column.limit ? value.to_s.mb_chars[0, column.limit] : value.to_s
810
- else
811
- comparison_operator = "= ?"
812
- end
813
-
814
- sql_attribute = "#{record.class.quoted_table_name}.#{connection.quote_column_name(attr_name)}"
815
-
816
- if value.nil? || (configuration[:case_sensitive] || !column.text?)
817
- condition_sql = "#{sql_attribute} #{comparison_operator}"
818
- condition_params = [value]
819
- else
820
- condition_sql = "LOWER(#{sql_attribute}) #{comparison_operator}"
821
- condition_params = [value.mb_chars.downcase]
822
- end
823
-
824
- if scope = configuration[:scope]
825
- Array(scope).map do |scope_item|
826
- scope_value = record.send(scope_item)
827
- condition_sql << " AND " << attribute_condition("#{record.class.quoted_table_name}.#{connection.quote_column_name(scope_item)}", scope_value)
828
- condition_params << scope_value
829
- end
830
- end
831
-
832
- unless record.new_record?
833
- condition_sql << " AND #{record.class.quoted_table_name}.#{record.class.primary_key} <> ?"
834
- condition_params << record.send(:id)
835
- end
836
-
837
- finder_class.with_exclusive_scope do
838
- if finder_class.exists?([condition_sql, *condition_params])
839
- record.errors.add(attr_name, :taken, :default => configuration[:message], :value => value)
840
- end
841
- end
842
- end
843
- end
844
-
845
-
846
- # Validates whether the value of the specified attribute is of the correct form by matching it against the regular expression
847
- # provided.
848
- #
849
- # class Person < ActiveRecord::Base
850
- # validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
851
- # end
852
- #
853
- # Note: use <tt>\A</tt> and <tt>\Z</tt> to match the start and end of the string, <tt>^</tt> and <tt>$</tt> match the start/end of a line.
854
- #
855
- # A regular expression must be provided or else an exception will be raised.
856
- #
857
- # Configuration options:
858
- # * <tt>:message</tt> - A custom error message (default is: "is invalid").
859
- # * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
860
- # * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
861
- # * <tt>:with</tt> - The regular expression used to validate the format with (note: must be supplied!).
862
- # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
863
- # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
864
- # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
865
- # method, proc or string should return or evaluate to a true or false value.
866
- # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
867
- # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
868
- # method, proc or string should return or evaluate to a true or false value.
869
- def validates_format_of(*attr_names)
870
- configuration = { :on => :save, :with => nil }
871
- configuration.update(attr_names.extract_options!)
872
-
873
- raise(ArgumentError, "A regular expression must be supplied as the :with option of the configuration hash") unless configuration[:with].is_a?(Regexp)
874
-
875
- validates_each(attr_names, configuration) do |record, attr_name, value|
876
- unless value.to_s =~ configuration[:with]
877
- record.errors.add(attr_name, :invalid, :default => configuration[:message], :value => value)
878
- end
879
- end
880
- end
881
-
882
- # Validates whether the value of the specified attribute is available in a particular enumerable object.
883
- #
884
- # class Person < ActiveRecord::Base
885
- # validates_inclusion_of :gender, :in => %w( m f )
886
- # validates_inclusion_of :age, :in => 0..99
887
- # validates_inclusion_of :format, :in => %w( jpg gif png ), :message => "extension %{value} is not included in the list"
888
- # end
889
- #
890
- # Configuration options:
891
- # * <tt>:in</tt> - An enumerable object of available items.
892
- # * <tt>:message</tt> - Specifies a custom error message (default is: "is not included in the list").
893
- # * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
894
- # * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
895
- # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
896
- # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
897
- # method, proc or string should return or evaluate to a true or false value.
898
- # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
899
- # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
900
- # method, proc or string should return or evaluate to a true or false value.
901
- def validates_inclusion_of(*attr_names)
902
- configuration = { :on => :save }
903
- configuration.update(attr_names.extract_options!)
904
-
905
- enum = configuration[:in] || configuration[:within]
906
-
907
- raise(ArgumentError, "An object with the method include? is required must be supplied as the :in option of the configuration hash") unless enum.respond_to?(:include?)
908
-
909
- validates_each(attr_names, configuration) do |record, attr_name, value|
910
- unless enum.include?(value)
911
- record.errors.add(attr_name, :inclusion, :default => configuration[:message], :value => value)
912
- end
913
- end
914
- end
915
-
916
- # Validates that the value of the specified attribute is not in a particular enumerable object.
917
- #
918
- # class Person < ActiveRecord::Base
919
- # validates_exclusion_of :username, :in => %w( admin superuser ), :message => "You don't belong here"
920
- # validates_exclusion_of :age, :in => 30..60, :message => "This site is only for under 30 and over 60"
921
- # validates_exclusion_of :format, :in => %w( mov avi ), :message => "extension %{value} is not allowed"
922
- # end
923
- #
924
- # Configuration options:
925
- # * <tt>:in</tt> - An enumerable object of items that the value shouldn't be part of.
926
- # * <tt>:message</tt> - Specifies a custom error message (default is: "is reserved").
927
- # * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
928
- # * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
929
- # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
930
- # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
931
- # method, proc or string should return or evaluate to a true or false value.
932
- # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
933
- # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
934
- # method, proc or string should return or evaluate to a true or false value.
935
- def validates_exclusion_of(*attr_names)
936
- configuration = { :on => :save }
937
- configuration.update(attr_names.extract_options!)
938
-
939
- enum = configuration[:in] || configuration[:within]
940
-
941
- raise(ArgumentError, "An object with the method include? is required must be supplied as the :in option of the configuration hash") unless enum.respond_to?(:include?)
942
-
943
- validates_each(attr_names, configuration) do |record, attr_name, value|
944
- if enum.include?(value)
945
- record.errors.add(attr_name, :exclusion, :default => configuration[:message], :value => value)
946
- end
947
- end
948
- end
949
-
950
- # Validates whether the associated object or objects are all valid themselves. Works with any kind of association.
951
- #
952
- # class Book < ActiveRecord::Base
953
- # has_many :pages
954
- # belongs_to :library
955
- #
956
- # validates_associated :pages, :library
957
- # end
958
- #
959
- # Warning: If, after the above definition, you then wrote:
960
- #
961
- # class Page < ActiveRecord::Base
962
- # belongs_to :book
963
- #
964
- # validates_associated :book
965
- # end
966
- #
967
- # this would specify a circular dependency and cause infinite recursion.
968
- #
969
- # NOTE: This validation will not fail if the association hasn't been assigned. If you want to ensure that the association
970
- # is both present and guaranteed to be valid, you also need to use +validates_presence_of+.
971
- #
972
- # Configuration options:
973
- # * <tt>:message</tt> - A custom error message (default is: "is invalid")
974
- # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
975
- # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
976
- # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
977
- # method, proc or string should return or evaluate to a true or false value.
978
- # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
979
- # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
980
- # method, proc or string should return or evaluate to a true or false value.
981
- def validates_associated(*attr_names)
982
- configuration = { :on => :save }
983
- configuration.update(attr_names.extract_options!)
984
-
985
- validates_each(attr_names, configuration) do |record, attr_name, value|
986
- unless (value.is_a?(Array) ? value : [value]).collect { |r| r.nil? || r.valid? }.all?
987
- record.errors.add(attr_name, :invalid, :default => configuration[:message], :value => value)
988
- end
989
- end
990
- end
991
-
992
- # Validates whether the value of the specified attribute is numeric by trying to convert it to
993
- # a float with Kernel.Float (if <tt>only_integer</tt> is false) or applying it to the regular expression
994
- # <tt>/\A[\+\-]?\d+\Z/</tt> (if <tt>only_integer</tt> is set to true).
995
- #
996
- # class Person < ActiveRecord::Base
997
- # validates_numericality_of :value, :on => :create
998
- # end
999
- #
1000
- # Configuration options:
1001
- # * <tt>:message</tt> - A custom error message (default is: "is not a number").
1002
- # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
1003
- # * <tt>:only_integer</tt> - Specifies whether the value has to be an integer, e.g. an integral value (default is +false+).
1004
- # * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default is +false+). Notice that for fixnum and float columns empty strings are converted to +nil+.
1005
- # * <tt>:greater_than</tt> - Specifies the value must be greater than the supplied value.
1006
- # * <tt>:greater_than_or_equal_to</tt> - Specifies the value must be greater than or equal the supplied value.
1007
- # * <tt>:equal_to</tt> - Specifies the value must be equal to the supplied value.
1008
- # * <tt>:less_than</tt> - Specifies the value must be less than the supplied value.
1009
- # * <tt>:less_than_or_equal_to</tt> - Specifies the value must be less than or equal the supplied value.
1010
- # * <tt>:odd</tt> - Specifies the value must be an odd number.
1011
- # * <tt>:even</tt> - Specifies the value must be an even number.
1012
- # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
1013
- # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
1014
- # method, proc or string should return or evaluate to a true or false value.
1015
- # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
1016
- # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
1017
- # method, proc or string should return or evaluate to a true or false value.
1018
- def validates_numericality_of(*attr_names)
1019
- configuration = { :on => :save, :only_integer => false, :allow_nil => false }
1020
- configuration.update(attr_names.extract_options!)
1021
-
1022
-
1023
- numericality_options = ALL_NUMERICALITY_CHECKS.keys & configuration.keys
1024
-
1025
- (numericality_options - [ :odd, :even ]).each do |option|
1026
- raise ArgumentError, ":#{option} must be a number" unless configuration[option].is_a?(Numeric)
1027
- end
1028
-
1029
- validates_each(attr_names,configuration) do |record, attr_name, value|
1030
- raw_value = record.send("#{attr_name}_before_type_cast") || value
1031
-
1032
- next if configuration[:allow_nil] and raw_value.nil?
1033
-
1034
- if configuration[:only_integer]
1035
- unless raw_value.to_s =~ /\A[+-]?\d+\Z/
1036
- record.errors.add(attr_name, :not_a_number, :value => raw_value, :default => configuration[:message])
1037
- next
1038
- end
1039
- raw_value = raw_value.to_i
1040
- else
1041
- begin
1042
- raw_value = Kernel.Float(raw_value)
1043
- rescue ArgumentError, TypeError
1044
- record.errors.add(attr_name, :not_a_number, :value => raw_value, :default => configuration[:message])
1045
- next
1046
- end
1047
- end
1048
-
1049
- numericality_options.each do |option|
1050
- case option
1051
- when :odd, :even
1052
- unless raw_value.to_i.method(ALL_NUMERICALITY_CHECKS[option])[]
1053
- record.errors.add(attr_name, option, :value => raw_value, :default => configuration[:message])
1054
- end
1055
- else
1056
- record.errors.add(attr_name, option, :default => configuration[:message], :value => raw_value, :count => configuration[option]) unless raw_value.method(ALL_NUMERICALITY_CHECKS[option])[configuration[option]]
1057
- end
1058
- end
1059
- end
1060
- end
1061
-
1062
28
  # Creates an object just like Base.create but calls save! instead of save
1063
29
  # so an exception is raised if the record is invalid.
1064
30
  def create!(attributes = nil, &block)
@@ -1071,76 +37,61 @@ module ActiveRecord
1071
37
  object
1072
38
  end
1073
39
  end
1074
-
1075
- private
1076
- def validation_method(on)
1077
- case on
1078
- when :save then :validate
1079
- when :create then :validate_on_create
1080
- when :update then :validate_on_update
1081
- end
1082
- end
1083
40
  end
1084
41
 
1085
- # The validation process on save can be skipped by passing false. The regular Base#save method is
1086
- # replaced with this when the validations module is mixed in, which it is by default.
1087
- def save_with_validation(perform_validation = true)
1088
- if perform_validation && valid? || !perform_validation
1089
- save_without_validation
1090
- else
1091
- false
1092
- end
1093
- end
42
+ module InstanceMethods
43
+ # The validation process on save can be skipped by passing false. The regular Base#save method is
44
+ # replaced with this when the validations module is mixed in, which it is by default.
45
+ def save_with_validation(options=nil)
46
+ perform_validation = case options
47
+ when NilClass
48
+ true
49
+ when Hash
50
+ options[:validate] != false
51
+ else
52
+ ActiveSupport::Deprecation.warn "save(#{options}) is deprecated, please give save(:validate => #{options}) instead", caller
53
+ options
54
+ end
1094
55
 
1095
- # Attempts to save the record just like Base#save but will raise a RecordInvalid exception instead of returning false
1096
- # if the record is not valid.
1097
- def save_with_validation!
1098
- if valid?
1099
- save_without_validation!
1100
- else
1101
- raise RecordInvalid.new(self)
56
+ if perform_validation && valid? || !perform_validation
57
+ save_without_validation
58
+ else
59
+ false
60
+ end
1102
61
  end
1103
- end
1104
-
1105
- # Runs +validate+ and +validate_on_create+ or +validate_on_update+ and returns true if no errors were added otherwise false.
1106
- def valid?
1107
- errors.clear
1108
-
1109
- run_callbacks(:validate)
1110
- validate
1111
62
 
1112
- if new_record?
1113
- run_callbacks(:validate_on_create)
1114
- validate_on_create
1115
- else
1116
- run_callbacks(:validate_on_update)
1117
- validate_on_update
63
+ # Attempts to save the record just like Base#save but will raise a RecordInvalid exception instead of returning false
64
+ # if the record is not valid.
65
+ def save_with_validation!
66
+ if valid?
67
+ save_without_validation!
68
+ else
69
+ raise RecordInvalid.new(self)
70
+ end
1118
71
  end
1119
72
 
1120
- errors.empty?
1121
- end
1122
-
1123
- # Performs the opposite of <tt>valid?</tt>. Returns true if errors were added, false otherwise.
1124
- def invalid?
1125
- !valid?
1126
- end
73
+ # Runs all the specified validations and returns true if no errors were added otherwise false.
74
+ def valid?
75
+ errors.clear
1127
76
 
1128
- # Returns the Errors object that holds all information about attribute error messages.
1129
- def errors
1130
- @errors ||= Errors.new(self)
1131
- end
77
+ @_on_validate = new_record? ? :create : :update
78
+ _run_validate_callbacks
1132
79
 
1133
- protected
1134
- # Overwrite this method for validation checks on all saves and use <tt>Errors.add(field, msg)</tt> for invalid attributes.
1135
- def validate
1136
- end
80
+ deprecated_callback_method(:validate)
1137
81
 
1138
- # Overwrite this method for validation checks used only on creation.
1139
- def validate_on_create
1140
- end
82
+ if new_record?
83
+ deprecated_callback_method(:validate_on_create)
84
+ else
85
+ deprecated_callback_method(:validate_on_update)
86
+ end
1141
87
 
1142
- # Overwrite this method for validation checks used only on updates.
1143
- def validate_on_update
88
+ errors.empty?
1144
89
  end
90
+ end
1145
91
  end
1146
92
  end
93
+
94
+ Dir[File.dirname(__FILE__) + "/validations/*.rb"].sort.each do |path|
95
+ filename = File.basename(path)
96
+ require "active_record/validations/#{filename}"
97
+ end