rails 2.2.3 → 2.3.2

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

Potentially problematic release.


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

Files changed (229) hide show
  1. data/CHANGELOG +272 -191
  2. data/MIT-LICENSE +1 -1
  3. data/README +6 -19
  4. data/Rakefile +24 -71
  5. data/bin/rails +1 -0
  6. data/builtin/rails_info/rails/info.rb +12 -8
  7. data/configs/databases/mysql.yml +3 -0
  8. data/configs/initializers/backtrace_silencers.rb +7 -0
  9. data/configs/initializers/new_rails_defaults.rb +2 -0
  10. data/configs/initializers/session_store.rb +15 -0
  11. data/dispatches/config.ru +7 -0
  12. data/doc/README_FOR_APP +2 -5
  13. data/environments/boot.rb +1 -0
  14. data/environments/environment.rb +14 -48
  15. data/environments/production.rb +11 -7
  16. data/environments/test.rb +6 -0
  17. data/helpers/application_controller.rb +10 -0
  18. data/helpers/test_helper.rb +1 -1
  19. data/html/500.html +0 -3
  20. data/html/index.html +1 -0
  21. data/lib/commands/about.rb +1 -1
  22. data/lib/commands/dbconsole.rb +18 -2
  23. data/lib/commands/plugin.rb +4 -3
  24. data/lib/commands/runner.rb +13 -7
  25. data/lib/commands/server.rb +98 -33
  26. data/lib/console_app.rb +4 -4
  27. data/lib/console_with_helpers.rb +2 -23
  28. data/lib/dispatcher.rb +1 -1
  29. data/lib/fcgi_handler.rb +12 -10
  30. data/lib/initializer.rb +108 -41
  31. data/lib/rails/backtrace_cleaner.rb +54 -0
  32. data/lib/rails/gem_dependency.rb +124 -94
  33. data/lib/rails/plugin.rb +49 -6
  34. data/lib/rails/plugin/loader.rb +66 -27
  35. data/lib/rails/plugin/locator.rb +1 -1
  36. data/lib/rails/rack.rb +3 -1
  37. data/lib/rails/rack/debugger.rb +21 -0
  38. data/lib/rails/rack/log_tailer.rb +35 -0
  39. data/lib/rails/rack/metal.rb +51 -0
  40. data/lib/rails/rack/static.rb +15 -4
  41. data/lib/rails/version.rb +2 -2
  42. data/lib/rails_generator/base.rb +3 -0
  43. data/lib/rails_generator/commands.rb +8 -3
  44. data/lib/rails_generator/generators/applications/app/app_generator.rb +210 -136
  45. data/lib/rails_generator/generators/applications/app/scm/git.rb +16 -0
  46. data/lib/rails_generator/generators/applications/app/scm/scm.rb +8 -0
  47. data/lib/rails_generator/generators/applications/app/scm/svn.rb +7 -0
  48. data/lib/rails_generator/generators/applications/app/template_runner.rb +401 -0
  49. data/lib/rails_generator/generators/components/controller/USAGE +12 -11
  50. data/lib/rails_generator/generators/components/controller/controller_generator.rb +7 -1
  51. data/lib/rails_generator/generators/components/controller/templates/helper_test.rb +4 -0
  52. data/lib/rails_generator/generators/components/helper/USAGE +24 -0
  53. data/lib/rails_generator/generators/components/helper/helper_generator.rb +25 -0
  54. data/lib/rails_generator/generators/components/helper/templates/helper.rb +2 -0
  55. data/lib/rails_generator/generators/components/helper/templates/helper_test.rb +4 -0
  56. data/lib/rails_generator/generators/components/metal/USAGE +8 -0
  57. data/lib/rails_generator/generators/components/metal/metal_generator.rb +8 -0
  58. data/lib/rails_generator/generators/components/metal/templates/metal.rb +12 -0
  59. data/lib/rails_generator/generators/components/resource/USAGE +2 -2
  60. data/lib/rails_generator/generators/components/resource/resource_generator.rb +2 -0
  61. data/lib/rails_generator/generators/components/resource/templates/helper_test.rb +4 -0
  62. data/lib/rails_generator/generators/components/scaffold/scaffold_generator.rb +2 -0
  63. data/lib/rails_generator/generators/components/scaffold/templates/controller.rb +1 -1
  64. data/lib/rails_generator/generators/components/scaffold/templates/functional_test.rb +4 -4
  65. data/lib/rails_generator/generators/components/scaffold/templates/helper_test.rb +4 -0
  66. data/lib/rails_generator/generators/components/scaffold/templates/layout.html.erb +1 -1
  67. data/lib/rails_generator/generators/components/scaffold/templates/view_edit.html.erb +2 -2
  68. data/lib/rails_generator/generators/components/scaffold/templates/view_index.html.erb +2 -2
  69. data/lib/rails_generator/generators/components/scaffold/templates/view_new.html.erb +2 -2
  70. data/lib/rails_generator/generators/components/scaffold/templates/view_show.html.erb +1 -1
  71. data/lib/rails_generator/secret_key_generator.rb +2 -0
  72. data/lib/tasks/databases.rake +13 -6
  73. data/lib/tasks/documentation.rake +2 -9
  74. data/lib/tasks/framework.rake +26 -1
  75. data/lib/tasks/gems.rake +33 -48
  76. data/lib/tasks/middleware.rake +7 -0
  77. data/lib/tasks/misc.rake +7 -0
  78. data/lib/tasks/statistics.rake +0 -1
  79. data/lib/tasks/testing.rake +5 -5
  80. data/lib/tasks/tmp.rake +2 -2
  81. data/lib/test_help.rb +16 -8
  82. metadata +92 -159
  83. data/bin/performance/request +0 -3
  84. data/bin/process/inspector +0 -3
  85. data/bin/process/reaper +0 -3
  86. data/bin/process/spawner +0 -3
  87. data/config.ru +0 -17
  88. data/configs/apache.conf +0 -40
  89. data/configs/lighttpd.conf +0 -54
  90. data/doc/guides/html/2_2_release_notes.html +0 -1185
  91. data/doc/guides/html/actioncontroller_basics.html +0 -1270
  92. data/doc/guides/html/activerecord_validations_callbacks.html +0 -749
  93. data/doc/guides/html/association_basics.html +0 -2585
  94. data/doc/guides/html/authors.html +0 -240
  95. data/doc/guides/html/benchmarking_and_profiling.html +0 -1018
  96. data/doc/guides/html/caching_with_rails.html +0 -583
  97. data/doc/guides/html/command_line.html +0 -434
  98. data/doc/guides/html/configuring.html +0 -438
  99. data/doc/guides/html/creating_plugins.html +0 -1594
  100. data/doc/guides/html/debugging_rails_applications.html +0 -1175
  101. data/doc/guides/html/finders.html +0 -1090
  102. data/doc/guides/html/form_helpers.html +0 -638
  103. data/doc/guides/html/getting_started_with_rails.html +0 -2066
  104. data/doc/guides/html/index.html +0 -349
  105. data/doc/guides/html/layouts_and_rendering.html +0 -1406
  106. data/doc/guides/html/migrations.html +0 -921
  107. data/doc/guides/html/routing_outside_in.html +0 -2213
  108. data/doc/guides/html/security.html +0 -1346
  109. data/doc/guides/html/testing_rails_applications.html +0 -1859
  110. data/doc/guides/source/2_2_release_notes.txt +0 -435
  111. data/doc/guides/source/actioncontroller_basics/changelog.txt +0 -5
  112. data/doc/guides/source/actioncontroller_basics/cookies.txt +0 -34
  113. data/doc/guides/source/actioncontroller_basics/csrf.txt +0 -32
  114. data/doc/guides/source/actioncontroller_basics/filters.txt +0 -119
  115. data/doc/guides/source/actioncontroller_basics/http_auth.txt +0 -24
  116. data/doc/guides/source/actioncontroller_basics/index.txt +0 -40
  117. data/doc/guides/source/actioncontroller_basics/introduction.txt +0 -9
  118. data/doc/guides/source/actioncontroller_basics/methods.txt +0 -39
  119. data/doc/guides/source/actioncontroller_basics/parameter_filtering.txt +0 -14
  120. data/doc/guides/source/actioncontroller_basics/params.txt +0 -93
  121. data/doc/guides/source/actioncontroller_basics/request_response_objects.txt +0 -43
  122. data/doc/guides/source/actioncontroller_basics/rescue.txt +0 -67
  123. data/doc/guides/source/actioncontroller_basics/session.txt +0 -187
  124. data/doc/guides/source/actioncontroller_basics/streaming.txt +0 -91
  125. data/doc/guides/source/actioncontroller_basics/verification.txt +0 -40
  126. data/doc/guides/source/active_record_basics.txt +0 -181
  127. data/doc/guides/source/activerecord_validations_callbacks.txt +0 -404
  128. data/doc/guides/source/association_basics.txt +0 -1840
  129. data/doc/guides/source/authors.txt +0 -39
  130. data/doc/guides/source/benchmarking_and_profiling/appendix.txt +0 -95
  131. data/doc/guides/source/benchmarking_and_profiling/digging_deeper.txt +0 -105
  132. data/doc/guides/source/benchmarking_and_profiling/edge_rails_features.txt +0 -185
  133. data/doc/guides/source/benchmarking_and_profiling/gameplan.txt +0 -27
  134. data/doc/guides/source/benchmarking_and_profiling/index.txt +0 -242
  135. data/doc/guides/source/benchmarking_and_profiling/rubyprof.txt +0 -179
  136. data/doc/guides/source/benchmarking_and_profiling/statistics.txt +0 -57
  137. data/doc/guides/source/caching_with_rails.txt +0 -367
  138. data/doc/guides/source/command_line.txt +0 -147
  139. data/doc/guides/source/configuring.txt +0 -225
  140. data/doc/guides/source/creating_plugins/acts_as_yaffle.txt +0 -191
  141. data/doc/guides/source/creating_plugins/appendix.txt +0 -46
  142. data/doc/guides/source/creating_plugins/controllers.txt +0 -59
  143. data/doc/guides/source/creating_plugins/core_ext.txt +0 -123
  144. data/doc/guides/source/creating_plugins/custom_route.txt +0 -69
  145. data/doc/guides/source/creating_plugins/gem.txt +0 -1
  146. data/doc/guides/source/creating_plugins/generator_method.txt +0 -89
  147. data/doc/guides/source/creating_plugins/helpers.txt +0 -51
  148. data/doc/guides/source/creating_plugins/index.txt +0 -52
  149. data/doc/guides/source/creating_plugins/migration_generator.txt +0 -156
  150. data/doc/guides/source/creating_plugins/models.txt +0 -76
  151. data/doc/guides/source/creating_plugins/odds_and_ends.txt +0 -69
  152. data/doc/guides/source/creating_plugins/test_setup.txt +0 -230
  153. data/doc/guides/source/debugging_rails_applications.txt +0 -733
  154. data/doc/guides/source/finders.txt +0 -668
  155. data/doc/guides/source/form_helpers.txt +0 -345
  156. data/doc/guides/source/getting_started_with_rails.txt +0 -1256
  157. data/doc/guides/source/images/belongs_to.png +0 -0
  158. data/doc/guides/source/images/bullet.gif +0 -0
  159. data/doc/guides/source/images/csrf.png +0 -0
  160. data/doc/guides/source/images/habtm.png +0 -0
  161. data/doc/guides/source/images/has_many.png +0 -0
  162. data/doc/guides/source/images/has_many_through.png +0 -0
  163. data/doc/guides/source/images/has_one.png +0 -0
  164. data/doc/guides/source/images/has_one_through.png +0 -0
  165. data/doc/guides/source/images/header_backdrop.png +0 -0
  166. data/doc/guides/source/images/icons/README +0 -5
  167. data/doc/guides/source/images/icons/callouts/1.png +0 -0
  168. data/doc/guides/source/images/icons/callouts/10.png +0 -0
  169. data/doc/guides/source/images/icons/callouts/11.png +0 -0
  170. data/doc/guides/source/images/icons/callouts/12.png +0 -0
  171. data/doc/guides/source/images/icons/callouts/13.png +0 -0
  172. data/doc/guides/source/images/icons/callouts/14.png +0 -0
  173. data/doc/guides/source/images/icons/callouts/15.png +0 -0
  174. data/doc/guides/source/images/icons/callouts/2.png +0 -0
  175. data/doc/guides/source/images/icons/callouts/3.png +0 -0
  176. data/doc/guides/source/images/icons/callouts/4.png +0 -0
  177. data/doc/guides/source/images/icons/callouts/5.png +0 -0
  178. data/doc/guides/source/images/icons/callouts/6.png +0 -0
  179. data/doc/guides/source/images/icons/callouts/7.png +0 -0
  180. data/doc/guides/source/images/icons/callouts/8.png +0 -0
  181. data/doc/guides/source/images/icons/callouts/9.png +0 -0
  182. data/doc/guides/source/images/icons/caution.png +0 -0
  183. data/doc/guides/source/images/icons/example.png +0 -0
  184. data/doc/guides/source/images/icons/home.png +0 -0
  185. data/doc/guides/source/images/icons/important.png +0 -0
  186. data/doc/guides/source/images/icons/next.png +0 -0
  187. data/doc/guides/source/images/icons/note.png +0 -0
  188. data/doc/guides/source/images/icons/prev.png +0 -0
  189. data/doc/guides/source/images/icons/tip.png +0 -0
  190. data/doc/guides/source/images/icons/up.png +0 -0
  191. data/doc/guides/source/images/icons/warning.png +0 -0
  192. data/doc/guides/source/images/polymorphic.png +0 -0
  193. data/doc/guides/source/images/rails_logo_remix.gif +0 -0
  194. data/doc/guides/source/images/ruby_on_rails_by_mike_rundle2.gif +0 -0
  195. data/doc/guides/source/images/session_fixation.png +0 -0
  196. data/doc/guides/source/index.txt +0 -118
  197. data/doc/guides/source/layouts_and_rendering.txt +0 -982
  198. data/doc/guides/source/migrations/anatomy_of_a_migration.txt +0 -85
  199. data/doc/guides/source/migrations/changelog.txt +0 -5
  200. data/doc/guides/source/migrations/creating_a_migration.txt +0 -109
  201. data/doc/guides/source/migrations/foreign_keys.txt +0 -8
  202. data/doc/guides/source/migrations/index.txt +0 -22
  203. data/doc/guides/source/migrations/rakeing_around.txt +0 -111
  204. data/doc/guides/source/migrations/scheming.txt +0 -47
  205. data/doc/guides/source/migrations/using_models_in_migrations.txt +0 -46
  206. data/doc/guides/source/migrations/writing_a_migration.txt +0 -159
  207. data/doc/guides/source/routing_outside_in.txt +0 -986
  208. data/doc/guides/source/security.txt +0 -984
  209. data/doc/guides/source/stylesheets/base.css +0 -358
  210. data/doc/guides/source/stylesheets/forms.css +0 -35
  211. data/doc/guides/source/stylesheets/more.css +0 -82
  212. data/doc/guides/source/templates/guides.html.erb +0 -97
  213. data/doc/guides/source/templates/inline.css +0 -165
  214. data/doc/guides/source/testing_rails_applications.txt +0 -995
  215. data/helpers/application.rb +0 -15
  216. data/lib/commands/performance/request.rb +0 -6
  217. data/lib/commands/process/inspector.rb +0 -68
  218. data/lib/commands/process/reaper.rb +0 -149
  219. data/lib/commands/process/spawner.rb +0 -219
  220. data/lib/commands/process/spinner.rb +0 -57
  221. data/lib/commands/servers/base.rb +0 -31
  222. data/lib/commands/servers/lighttpd.rb +0 -94
  223. data/lib/commands/servers/mongrel.rb +0 -69
  224. data/lib/commands/servers/new_mongrel.rb +0 -16
  225. data/lib/commands/servers/thin.rb +0 -25
  226. data/lib/commands/servers/webrick.rb +0 -66
  227. data/lib/rails/mongrel_server/commands.rb +0 -342
  228. data/lib/rails/mongrel_server/handler.rb +0 -55
  229. data/lib/rails/rack/logger.rb +0 -28
@@ -1,668 +0,0 @@
1
- Rails Finders
2
- =============
3
-
4
- This guide covers the +find+ method defined in +ActiveRecord::Base+, as well as other ways of finding particular instances of your models. By using this guide, you will be able to:
5
-
6
- * Find records using a variety of methods and conditions
7
- * Specify the order, retrieved attributes, grouping, and other properties of the found records
8
- * Use eager loading to cut down on the number of database queries in your application
9
- * Use dynamic finders
10
- * Create named scopes to add custom finding behavior to your models
11
- * Check for the existence of particular records
12
- * Perform aggregate calculations on Active Record models
13
-
14
- If you're used to using raw SQL to find database records, you'll find that there are generally better ways to carry out the same operations in Rails. Active Record insulates you from the need to use SQL in most cases.
15
-
16
- == The Sample Models
17
-
18
- This guide demonstrates finding using the following models:
19
-
20
- [source,ruby]
21
- -------------------------------------------------------
22
- class Client < ActiveRecord::Base
23
- has_one :address
24
- has_one :mailing_address
25
- has_many :orders
26
- has_and_belongs_to_many :roles
27
- end
28
-
29
- class Address < ActiveRecord::Base
30
- belongs_to :client
31
- end
32
-
33
- class MailingAddress < Address
34
- end
35
-
36
- class Order < ActiveRecord::Base
37
- belongs_to :client, :counter_cache => true
38
- end
39
-
40
- class Role < ActiveRecord::Base
41
- has_and_belongs_to_many :clients
42
- end
43
- -------------------------------------------------------
44
-
45
- == Database Agnostic
46
-
47
- Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you're using, the Active Record method format will always be the same.
48
-
49
- == IDs, First, Last and All
50
-
51
- +ActiveRecord::Base+ has methods defined on it to make interacting with your database and the tables within it much, much easier. For finding records, the key method is +find+. This method allows you to pass arguments into it to perform certain queries on your database without the need of SQL. If you wanted to find the record with the id of 1, you could type +Client.find(1)+ which would execute this query on your database:
52
-
53
- [source, sql]
54
- -------------------------------------------------------
55
- SELECT * FROM +clients+ WHERE (+clients+.+id+ = 1)
56
- -------------------------------------------------------
57
-
58
- NOTE: Because this is a standard table created from a migration in Rail, the primary key is defaulted to 'id'. If you have specified a different primary key in your migrations, this is what Rails will find on when you call the find method, not the id column.
59
-
60
- If you wanted to find clients with id 1 or 2, you call +Client.find([1,2])+ or +Client.find(1,2)+ and then this will be executed as:
61
-
62
- [source, sql]
63
- -------------------------------------------------------
64
- SELECT * FROM +clients+ WHERE (+clients+.+id+ IN (1,2))
65
- -------------------------------------------------------
66
-
67
- -------------------------------------------------------
68
- >> Client.find(1,2)
69
- => [#<Client id: 1, name: => "Ryan", locked: false, orders_count: 2,
70
- created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">,
71
- #<Client id: 2, name: => "Michael", locked: false, orders_count: 3,
72
- created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">]
73
- -------------------------------------------------------
74
-
75
- Note that if you pass in a list of numbers that the result will be returned as an array, not as a single +Client+ object.
76
-
77
- NOTE: If +find(id)+ or +find([id1, id2])+ fails to find any records, it will raise a +RecordNotFound+ exception.
78
-
79
- If you wanted to find the first client you would simply type +Client.first+ and that would find the first client created in your clients table:
80
-
81
- -------------------------------------------------------
82
- >> Client.first
83
- => #<Client id: 1, name: => "Ryan", locked: false, orders_count: 2,
84
- created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">
85
- -------------------------------------------------------
86
-
87
- If you were running script/server you might see the following output:
88
-
89
- [source,sql]
90
- -------------------------------------------------------
91
- SELECT * FROM clients LIMIT 1
92
- -------------------------------------------------------
93
-
94
- Indicating the query that Rails has performed on your database.
95
-
96
- To find the last client you would simply type +Client.find(:last)+ and that would find the last client created in your clients table:
97
-
98
- -------------------------------------------------------
99
- >> Client.find(:last)
100
- => #<Client id: 2, name: => "Michael", locked: false, orders_count: 3,
101
- created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">
102
- -------------------------------------------------------
103
-
104
- [source,sql]
105
- -------------------------------------------------------
106
- SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
107
- -------------------------------------------------------
108
-
109
- To find all the clients you would simply type +Client.all+ and that would find all the clients in your clients table:
110
-
111
- -------------------------------------------------------
112
- >> Client.all
113
- => [#<Client id: 1, name: => "Ryan", locked: false, orders_count: 2,
114
- created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">,
115
- #<Client id: 2, name: => "Michael", locked: false, orders_count: 3,
116
- created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">]
117
- -------------------------------------------------------
118
-
119
- As alternatives to calling +Client.first+, +Client.last+, and +Client.all+, you can use the class methods +Client.first+, +Client.last+, and +Client.all+ instead. +Client.first+, +Client.last+ and +Client.all+ just call their longer counterparts: +Client.find(:first)+, +Client.find(:last)+ and +Client.find(:all)+ respectively.
120
-
121
- Be aware that +Client.first+/+Client.find(:first)+ and +Client.last+/+Client.find(:last)+ will both return a single object, where as +Client.all+/+Client.find(:all)+ will return an array of Client objects, just as passing in an array of ids to find will do also.
122
-
123
- == Conditions
124
-
125
- The +find+ method allows you to specify conditions to limit the records returned. You can specify conditions as a string, array, or hash.
126
-
127
- === Pure String Conditions ===
128
-
129
- If you'd like to add conditions to your find, you could just specify them in there, just like +Client.first(:conditions => "orders_count = '2'")+. This will find all clients where the +orders_count+ field's value is 2.
130
-
131
- WARNING: Building your own conditions as pure strings can leave you vulnerable to SQL injection exploits. For example, +Client.first(:conditions => "name LIKE '%#{params[:name]}%'")+ is not safe. See the next section for the preferred way to handle conditions using an array.
132
-
133
- === Array Conditions ===
134
-
135
- Now what if that number could vary, say as a parameter from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like +Client.first(:conditions => ["orders_count = ?", params[:orders]])+. Active Record will go through the first element in the conditions value and any additional elements will replace the question marks (?) in the first element. If you want to specify two conditions, you can do it like +Client.first(:conditions => ["orders_count = ? AND locked = ?", params[:orders], false])+. In this example, the first question mark will be replaced with the value in params orders and the second will be replaced with true and this will find the first record in the table that has '2' as its value for the orders_count field and 'false' for its locked field.
136
-
137
- The reason for doing code like:
138
-
139
- [source, ruby]
140
- -------------------------------------------------------
141
- +Client.first(:conditions => ["orders_count = ?", params[:orders]])+
142
- -------------------------------------------------------
143
-
144
- instead of:
145
-
146
- -------------------------------------------------------
147
- +Client.first(:conditions => "orders_count = #{params[:orders]}")+
148
- -------------------------------------------------------
149
-
150
- is because of parameter safety. Putting the variable directly into the conditions string will pass the variable to the database *as-is*. This means that it will be an unescaped variable directly from a user who may have malicious intent. If you do this, you put your entire database at risk because once a user finds out he or she can exploit your database they can do just about anything to it. Never ever put your parameters directly inside the conditions string.
151
-
152
- TIP: For more information on the dangers of SQL injection, see the link:../security.html#_sql_injection[Ruby on Rails Security Guide].
153
-
154
- If you're looking for a range inside of a table (for example, users created in a certain timeframe) you can use the conditions option coupled with the IN sql statement for this. If you had two dates coming in from a controller you could do something like this to look for a range:
155
-
156
- [source, ruby]
157
- -------------------------------------------------------
158
- Client.all(:conditions => ["created_at IN (?)",
159
- (params[:start_date].to_date)..(params[:end_date].to_date)])
160
- -------------------------------------------------------
161
-
162
- This would generate the proper query which is great for small ranges but not so good for larger ranges. For example if you pass in a range of date objects spanning a year that's 365 (or possibly 366, depending on the year) strings it will attempt to match your field against.
163
-
164
- [source, sql]
165
- -------------------------------------------------------
166
- SELECT * FROM +users+ WHERE (created_at IN
167
- ('2007-12-31','2008-01-01','2008-01-02','2008-01-03','2008-01-04','2008-01-05',
168
- '2008-01-06','2008-01-07','2008-01-08','2008-01-09','2008-01-10','2008-01-11',
169
- '2008-01-12','2008-01-13','2008-01-14','2008-01-15','2008-01-16','2008-01-17',
170
- '2008-01-18','2008-01-19','2008-01-20','2008-01-21','2008-01-22','2008-01-23',...
171
- ‘2008-12-15','2008-12-16','2008-12-17','2008-12-18','2008-12-19','2008-12-20',
172
- '2008-12-21','2008-12-22','2008-12-23','2008-12-24','2008-12-25','2008-12-26',
173
- '2008-12-27','2008-12-28','2008-12-29','2008-12-30','2008-12-31'))
174
- -------------------------------------------------------
175
-
176
- Things can get *really* messy if you pass in time objects as it will attempt to compare your field to *every second* in that range:
177
-
178
- [source, ruby]
179
- -------------------------------------------------------
180
- Client.all(:conditions => ["created_at IN (?)",
181
- (params[:start_date].to_date.to_time)..(params[:end_date].to_date.to_time)])
182
- -------------------------------------------------------
183
-
184
- [source, sql]
185
- -------------------------------------------------------
186
- SELECT * FROM +users+ WHERE (created_at IN
187
- ('2007-12-01 00:00:00', '2007-12-01 00:00:01' ...
188
- '2007-12-01 23:59:59', '2007-12-02 00:00:00'))
189
- -------------------------------------------------------
190
-
191
- This could possibly cause your database server to raise an unexpected error, for example MySQL will throw back this error:
192
-
193
- -------------------------------------------------------
194
- Got a packet bigger than 'max_allowed_packet' bytes: _query_
195
- -------------------------------------------------------
196
-
197
- Where _query_ is the actual query used to get that error.
198
-
199
- In this example it would be better to use greater-than and less-than operators in SQL, like so:
200
-
201
- [source, ruby]
202
- -------------------------------------------------------
203
- Client.all(:conditions =>
204
- ["created_at > ? AND created_at < ?", params[:start_date], params[:end_date]])
205
- -------------------------------------------------------
206
-
207
- You can also use the greater-than-or-equal-to and less-than-or-equal-to like this:
208
-
209
- [source, ruby]
210
- -------------------------------------------------------
211
- Client.all(:conditions =>
212
- ["created_at >= ? AND created_at <= ?", params[:start_date], params[:end_date]])
213
- -------------------------------------------------------
214
-
215
- Just like in Ruby.
216
-
217
- === Hash Conditions ===
218
-
219
- Similar to the array style of params you can also specify keys in your conditions:
220
-
221
- [source, ruby]
222
- -------------------------------------------------------
223
- Client.all(:conditions =>
224
- ["created_at >= :start_date AND created_at <= :end_date", { :start_date => params[:start_date], :end_date => params[:end_date] }])
225
- -------------------------------------------------------
226
-
227
- This makes for clearer readability if you have a large number of variable conditions.
228
-
229
- == Ordering
230
-
231
- If you're getting a set of records and want to force an order, you can use +Client.all(:order => "created_at")+ which by default will sort the records by ascending order. If you'd like to order it in descending order, just tell it to do that using +Client.all(:order => "created_at desc")+
232
-
233
- == Selecting Certain Fields
234
-
235
- To select certain fields, you can use the select option like this: +Client.first(:select => "viewable_by, locked")+. This select option does not use an array of fields, but rather requires you to type SQL-like code. The above code will execute +SELECT viewable_by, locked FROM clients LIMIT 0,1+ on your database.
236
-
237
- == Limit & Offset
238
-
239
- If you want to limit the amount of records to a certain subset of all the records retrieved you usually use limit for this, sometimes coupled with offset. Limit is the maximum number of records that will be retrieved from a query, and offset is the number of records it will start reading from from the first record of the set. Take this code for example:
240
-
241
- [source, ruby]
242
- -------------------------------------------------------
243
- Client.all(:limit => 5)
244
- -------------------------------------------------------
245
-
246
- This code will return a maximum of 5 clients and because it specifies no offset it will return the first 5 clients in the table. The SQL it executes will look like this:
247
-
248
- [source,sql]
249
- -------------------------------------------------------
250
- SELECT * FROM clients LIMIT 5
251
- -------------------------------------------------------
252
-
253
- [source, ruby]
254
- -------------------------------------------------------
255
- Client.all(:limit => 5, :offset => 5)
256
- -------------------------------------------------------
257
-
258
- This code will return a maximum of 5 clients and because it specifies an offset this time, it will return these records starting from the 5th client in the clients table. The SQL looks like:
259
-
260
- [source,sql]
261
- -------------------------------------------------------
262
- SELECT * FROM clients LIMIT 5, 5
263
- -------------------------------------------------------
264
-
265
- == Group
266
-
267
- The group option for find is useful, for example, if you want to find a collection of the dates orders were created on. You could use the option in this context:
268
-
269
- [source, ruby]
270
- -------------------------------------------------------
271
- Order.all(:group => "date(created_at)", :order => "created_at")
272
- -------------------------------------------------------
273
-
274
- And this will give you a single +Order+ object for each date where there are orders in the database.
275
-
276
- The SQL that would be executed would be something like this:
277
-
278
- [source, sql]
279
- -------------------------------------------------------
280
- SELECT * FROM +orders+ GROUP BY date(created_at)
281
- -------------------------------------------------------
282
-
283
- == Read Only
284
-
285
- Readonly is a find option that you can set in order to make that instance of the record read-only. Any attempt to alter or destroy the record will not succeed, raising an +Active Record::ReadOnlyRecord+ exception. To set this option, specify it like this:
286
-
287
- [source, ruby]
288
- -------------------------------------------------------
289
- Client.first(:readonly => true)
290
- -------------------------------------------------------
291
-
292
- If you assign this record to a variable +client+, calling the following code will raise an +ActiveRecord::ReadOnlyRecord+ exception:
293
-
294
- [source, ruby]
295
- -------------------------------------------------------
296
- client = Client.first(:readonly => true)
297
- client.locked = false
298
- client.save
299
- -------------------------------------------------------
300
-
301
- == Lock
302
-
303
- If you're wanting to stop race conditions for a specific record (for example, you're incrementing a single field for a record, potentially from multiple simultaneous connections) you can use the lock option to ensure that the record is updated correctly. For safety, you should use this inside a transaction.
304
-
305
- [source, ruby]
306
- -------------------------------------------------------
307
- Topic.transaction do
308
- t = Topic.find(params[:id], :lock => true)
309
- t.increment!(:views)
310
- end
311
- -------------------------------------------------------
312
-
313
- == Making It All Work Together
314
-
315
- You can chain these options together in no particular order as Active Record will write the correct SQL for you. If you specify two instances of the same options inside the find statement Active Record will use the latter.
316
-
317
- == Eager Loading
318
-
319
- Eager loading is loading associated records along with any number of records in as few queries as possible. For example, if you wanted to load all the addresses associated with all the clients in a single query you could use +Client.all(:include => :address)+. If you wanted to include both the address and mailing address for the client you would use +Client.find(:all, :include => [:address, :mailing_address]). Include will first find the client records and then load the associated address records. Running script/server in one window, and executing the code through script/console in another window, the output should look similar to this:
320
-
321
- [source, sql]
322
- -------------------------------------------------------
323
- Client Load (0.000383) SELECT * FROM clients
324
- Address Load (0.119770) SELECT addresses.* FROM addresses
325
- WHERE (addresses.client_id IN (13,14))
326
- MailingAddress Load (0.001985) SELECT mailing_addresses.* FROM
327
- mailing_addresses WHERE (mailing_addresses.client_id IN (13,14))
328
- -------------------------------------------------------
329
-
330
- The numbers +13+ and +14+ in the above SQL are the ids of the clients gathered from the +Client.all+ query. Rails will then run a query to gather all the addresses and mailing addresses that have a client_id of 13 or 14. Although this is done in 3 queries, this is more efficient than not eager loading because without eager loading it would run a query for every time you called +address+ or +mailing_address+ on one of the objects in the clients array, which may lead to performance issues if you're loading a large number of records at once.
331
-
332
- If you wanted to get all the addresses for a client in the same query you would do +Client.all(:joins => :address)+ and you wanted to find the address and mailing address for that client you would do +Client.all(:joins => [:address, :mailing_address])+. This is more efficient because it does all the SQL in one query, as shown by this example:
333
-
334
- [source, sql]
335
- -------------------------------------------------------
336
- +Client Load (0.000455) SELECT clients.* FROM clients INNER JOIN addresses
337
- ON addresses.client_id = client.id INNER JOIN mailing_addresses ON
338
- mailing_addresses.client_id = client.id
339
- -------------------------------------------------------
340
-
341
- This query is more efficent, but there's a gotcha: if you have a client who does not have an address or a mailing address they will not be returned in this query at all. If you have any association as an optional association, you may want to use include rather than joins. Alternatively, you can use a SQL join clause to specify exactly the join you need (Rails always assumes an inner join):
342
-
343
- [source, ruby]
344
- -------------------------------------------------------
345
- Client.all(:joins => “LEFT OUTER JOIN addresses ON
346
- client.id = addresses.client_id LEFT OUTER JOIN mailing_addresses ON
347
- client.id = mailing_addresses.client_id”)
348
- -------------------------------------------------------
349
-
350
- When using eager loading you can specify conditions for the columns of the tables inside the eager loading to get back a smaller subset. If, for example, you want to find a client and all their orders within the last two weeks you could use eager loading with conditions for this:
351
-
352
- [source, ruby]
353
- -------------------------------------------------------
354
- Client.first(:include => "orders", :conditions =>
355
- ["orders.created_at >= ? AND orders.created_at <= ?", Time.now - 2.weeks, Time.now])
356
- -------------------------------------------------------
357
-
358
- == Dynamic finders
359
-
360
- For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called +name+ on your Client model for example, you get +find_by_name+ and +find_all_by_name+ for free from Active Record. If you have also have a +locked+ field on the client model, you also get +find_by_locked+ and +find_all_by_locked+. If you want to find both by name and locked, you can chain these finders together by simply typing +and+ between the fields for example +Client.find_by_name_and_locked('Ryan', true)+. These finders are an excellent alternative to using the conditions option, mainly because it's shorter to type +find_by_name(params[:name])+ than it is to type +first(:conditions => ["name = ?", params[:name]])+.
361
-
362
- There's another set of dynamic finders that let you find or create/initialize objects if they aren't find. These work in a similar fashion to the other finders and can be used like +find_or_create_by_name(params[:name])+. Using this will firstly perform a find and then create if the find returns nil. The SQL looks like this for +Client.find_or_create_by_name('Ryan')+:
363
-
364
- [source,sql]
365
- -------------------------------------------------------
366
- SELECT * FROM +clients+ WHERE (+clients+.+name+ = 'Ryan') LIMIT 1
367
- BEGIN
368
- INSERT INTO +clients+ (+name+, +updated_at+, +created_at+, +orders_count+, +locked+)
369
- VALUES('Ryan', '2008-09-28 15:39:12', '2008-09-28 15:39:12', '0', '0')
370
- COMMIT
371
- -------------------------------------------------------
372
-
373
- +find_or_create+'s sibling, +find_or_initialize+, will find an object and if it does not exist will call +new+ with the parameters you passed in. For example:
374
-
375
- [source, ruby]
376
- -------------------------------------------------------
377
- client = Client.find_or_initialize_by_name('Ryan')
378
- -------------------------------------------------------
379
-
380
- will either assign an existing client object with the name 'Ryan' to the client local variable, or initialize new object similar to calling +Client.new(:name => 'Ryan')+. From here, you can modify other fields in client by calling the attribute setters on it: +client.locked = true+ and when you want to write it to the database just call +save+ on it.
381
-
382
- == Finding By SQL
383
-
384
- If you'd like to use your own SQL to find records a table you can use +find_by_sql+. The +find_by_sql+ method will return an array of objects even if it only returns a single record in it's call to the database. For example you could run this query:
385
-
386
- [source, ruby]
387
- -------------------------------------------------------
388
- Client.find_by_sql("SELECT * FROM clients INNER JOIN orders ON clients.id = orders.client_id ORDER clients.created_at desc")
389
- -------------------------------------------------------
390
-
391
- +find_by_sql+ provides you with a simple way of making custom calls to the database and retrieving instantiated objects.
392
-
393
- == +select_all+ ==
394
-
395
- +find_by_sql+ has a close relative called +connection#select_all+. +select_all+ will retrieve objects from the database using custom SQL just like +find_by_sql+ but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record.
396
-
397
- [source, ruby]
398
- -------------------------------------------------------
399
- Client.connection.select_all("SELECT * FROM `clients` WHERE `id` = '1'")
400
- -------------------------------------------------------
401
-
402
- == Working with Associations
403
-
404
- When you define a has_many association on a model you get the find method and dynamic finders also on that association. This is helpful for finding associated records within the scope of an existing record, for example finding all the orders for a client that have been sent and not received by doing something like +Client.find(params[:id]).orders.find_by_sent_and_received(true, false)+. Having this find method available on associations is extremely helpful when using nested controllers.
405
-
406
- == Named Scopes
407
-
408
- Named scopes are another way to add custom finding behavior to the models in the application. Named scopes provide an object-oriented way to narrow the results of a query.
409
-
410
- === Simple Named Scopes
411
-
412
- Suppose want to find all clients who are male. You could use this code:
413
-
414
- [source, ruby]
415
- -------------------------------------------------------
416
- class Client < ActiveRecord::Base
417
- named_scope :males, :conditions => { :gender => "male" }
418
- end
419
- -------------------------------------------------------
420
-
421
- Then you could call +Client.males.all+ to get all the clients who are male. Please note that if you do not specify the +all+ on the end you will get a +Scope+ object back, not a set of records which you do get back if you put the +all+ on the end.
422
-
423
- If you wanted to find all the clients who are active, you could use this:
424
-
425
- [source,ruby]
426
- -------------------------------------------------------
427
- class Client < ActiveRecord::Base
428
- named_scope :active, :conditions => { :active => true }
429
- end
430
- -------------------------------------------------------
431
-
432
- You can call this new named_scope with +Client.active.all+ and this will do the same query as if we just used +Client.all(:conditions => ["active = ?", true])+. Please be aware that the conditions syntax in named_scope and find is different and the two are not interchangeable. If you want to find the first client within this named scope you could do +Client.active.first+.
433
-
434
- === Combining Named Scopes
435
-
436
- If you wanted to find all the clients who are active and male you can stack the named scopes like this:
437
-
438
- [source, ruby]
439
- -------------------------------------------------------
440
- Client.males.active.all
441
- -------------------------------------------------------
442
-
443
- If you would then like to do a +all+ on that scope, you can. Just like an association, named scopes allow you to call +all+ on them:
444
-
445
- [source, ruby]
446
- -------------------------------------------------------
447
- Client.males.active.all(:conditions => ["age > ?", params[:age]])
448
- -------------------------------------------------------
449
-
450
- === Runtime Evaluation of Named Scope Conditions
451
-
452
- Consider the following code:
453
-
454
- [source, ruby]
455
- -------------------------------------------------------
456
- class Client < ActiveRecord::Base
457
- named_scope :recent, :conditions => { :created_at > 2.weeks.ago }
458
- end
459
- -------------------------------------------------------
460
-
461
- This looks like a standard named scope that defines a method called recent which gathers all records created any time between now and 2 weeks ago. That's correct for the first time the model is loaded but for any time after that, +2.weeks.ago+ is set to that same value, so you will consistently get records from a certain date until your model is reloaded by something like your application restarting. The way to fix this is to put the code in a lambda block:
462
-
463
- [source, ruby]
464
- -------------------------------------------------------
465
- class Client < ActiveRecord::Base
466
- named_scope :recent, lambda { { :conditions => ["created_at > ?", 2.weeks.ago] } }
467
- end
468
- -------------------------------------------------------
469
-
470
- And now every time the recent named scope is called, the code in the lambda block will be parsed, so you'll get actually 2 weeks ago from the code execution, not 2 weeks ago from the time the model was loaded.
471
-
472
- === Named Scopes with Multiple Models
473
-
474
- In a named scope you can use +:include+ and +:joins+ options just like in find.
475
-
476
- [source, ruby]
477
- -------------------------------------------------------
478
- class Client < ActiveRecord::Base
479
- named_scope :active_within_2_weeks, :joins => :order,
480
- lambda { { :conditions => ["orders.created_at > ?", 2.weeks.ago] } }
481
- end
482
- -------------------------------------------------------
483
-
484
- This method, called as +Client.active_within_2_weeks.all+, will return all clients who have placed orders in the past 2 weeks.
485
-
486
- === Arguments to Named Scopes
487
-
488
- If you want to pass a named scope a compulsory argument, just specify it as a block parameter like this:
489
-
490
- [source, ruby]
491
- -------------------------------------------------------
492
- class Client < ActiveRecord::Base
493
- named_scope :recent, lambda { |time| { :conditions => ["created_at > ?", time] } }
494
- end
495
- -------------------------------------------------------
496
-
497
- This will work if you call +Client.recent(2.weeks.ago).all+ but not if you call +Client.recent+. If you want to add an optional argument for this, you have to use the splat operator as the block's parameter.
498
-
499
- [source, ruby]
500
- -------------------------------------------------------
501
- class Client < ActiveRecord::Base
502
- named_scope :recent, lambda { |*args| { :conditions => ["created_at > ?", args.first || 2.weeks.ago] } }
503
- end
504
- -------------------------------------------------------
505
-
506
- This will work with +Client.recent(2.weeks.ago).all+ and +Client.recent.all+, with the latter always returning records with a created_at date between right now and 2 weeks ago.
507
-
508
- Remember that named scopes are stackable, so you will be able to do +Client.recent(2.weeks.ago).unlocked.all+ to find all clients created between right now and 2 weeks ago and have their locked field set to false.
509
-
510
- === Anonymous Scopes
511
-
512
- All Active Record models come with a named scope named +scoped+, which allows you to create anonymous scopes. For example:
513
-
514
- [source, ruby]
515
- -------------------------------------------------------
516
- class Client < ActiveRecord::Base
517
- def self.recent
518
- scoped :conditions => ["created_at > ?", 2.weeks.ago]
519
- end
520
- end
521
- -------------------------------------------------------
522
-
523
- Anonymous scopes are most useful to create scopes "on the fly":
524
-
525
- [source, ruby]
526
- -------------------------------------------------------
527
- Client.scoped(:conditions => { :gender => "male" })
528
- -------------------------------------------------------
529
-
530
- Just like named scopes, anonymous scopes can be stacked, either with other anonymous scopes or with regular named scopes.
531
-
532
- == Existence of Objects
533
-
534
- If you simply want to check for the existence of the object there's a method called +exists?+. This method will query the database using the same query as find, but instead of returning an object or collection of objects it will return either true or false.
535
-
536
- [source, ruby]
537
- -------------------------------------------------------
538
- Client.exists?(1)
539
- -------------------------------------------------------
540
-
541
- The above code will check for the existence of a clients table record with the id of 1 and return true if it exists.
542
-
543
- [source, ruby]
544
- -------------------------------------------------------
545
- Client.exists?(1,2,3)
546
- # or
547
- Client.exists?([1,2,3])
548
- -------------------------------------------------------
549
-
550
- The +exists?+ method also takes multiple ids, as shown by the above code, but the catch is that it will return true if any one of those records exists.
551
-
552
- Further more, +exists+ takes a +conditions+ option much like find:
553
-
554
- [source, ruby]
555
- -------------------------------------------------------
556
- Client.exists?(:conditions => "first_name = 'Ryan'")
557
- -------------------------------------------------------
558
-
559
- == Calculations
560
-
561
- This section uses count as an example method in this preamble, but the options described apply to all sub-sections.
562
-
563
- +count+ takes conditions much in the same way +exists?+ does:
564
-
565
- [source, ruby]
566
- -------------------------------------------------------
567
- Client.count(:conditions => "first_name = 'Ryan'")
568
- -------------------------------------------------------
569
-
570
- Which will execute:
571
-
572
- [source, sql]
573
- -------------------------------------------------------
574
- SELECT count(*) AS count_all FROM +clients+ WHERE (first_name = 1)
575
- -------------------------------------------------------
576
-
577
- You can also use +include+ or +joins+ for this to do something a little more complex:
578
-
579
- [source, ruby]
580
- -------------------------------------------------------
581
- Client.count(:conditions => "clients.first_name = 'Ryan' AND orders.status = 'received'", :include => "orders")
582
- -------------------------------------------------------
583
-
584
- Which will execute:
585
-
586
- [source, sql]
587
- -------------------------------------------------------
588
- SELECT count(DISTINCT +clients+.id) AS count_all FROM +clients+
589
- LEFT OUTER JOIN +orders+ ON orders.client_id = client.id WHERE
590
- (clients.first_name = 'name' AND orders.status = 'received')
591
- -------------------------------------------------------
592
-
593
- This code specifies +clients.first_name+ just in case one of the join tables has a field also called +first_name+ and it uses +orders.status+ because that's the name of our join table.
594
-
595
-
596
- === Count
597
-
598
- If you want to see how many records are in your model's table you could call +Client.count+ and that will return the number. If you want to be more specific and find all the clients with their age present in the database you can use +Client.count(:age)+.
599
-
600
- For options, please see the parent section, Calculations.
601
-
602
- === Average
603
-
604
- If you want to see the average of a certain number in one of your tables you can call the +average+ method on the class that relates to the table. This method call will look something like this:
605
-
606
- [source, ruby]
607
- -------------------------------------------------------
608
- Client.average("orders_count")
609
- -------------------------------------------------------
610
-
611
- This will return a number (possibly a floating point number such as 3.14159265) representing the average value in the field.
612
-
613
- For options, please see the parent section, <<_calculations, Calculations>>
614
-
615
- === Minimum
616
-
617
- If you want to find the minimum value of a field in your table you can call the +minimum+ method on the class that relates to the table. This method call will look something like this:
618
-
619
- [source, ruby]
620
- -------------------------------------------------------
621
- Client.minimum("age")
622
- -------------------------------------------------------
623
-
624
- For options, please see the parent section, <<_calculations, Calculations>>
625
-
626
- === Maximum
627
-
628
- If you want to find the maximum value of a field in your table you can call the +maximum+ method on the class that relates to the table. This method call will look something like this:
629
-
630
- [source, ruby]
631
- -------------------------------------------------------
632
- Client.maximum("age")
633
- -------------------------------------------------------
634
-
635
- For options, please see the parent section, <<_calculations, Calculations>>
636
-
637
- === Sum
638
-
639
- If you want to find the sum of a field for all records in your table you can call the +sum+ method on the class that relates to the table. This method call will look something like this:
640
-
641
- [source, ruby]
642
- -------------------------------------------------------
643
- Client.sum("orders_count")
644
- -------------------------------------------------------
645
-
646
- For options, please see the parent section, <<_calculations, Calculations>>
647
-
648
- == Credits
649
-
650
- Thanks to Ryan Bates for his awesome screencast on named scope #108. The information within the named scope section is intentionally similar to it, and without the cast may have not been possible.
651
-
652
- Thanks to Mike Gunderloy for his tips on creating this guide.
653
-
654
- == Changelog
655
-
656
- http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16[Lighthouse ticket]
657
-
658
- * November 8, 2008: Editing pass by link:../authors.html#mgunderloy[Mike Gunderloy] . First release version.
659
- * October 27, 2008: Added scoped section, added named params for conditions and added sub-section headers for conditions section by Ryan Bigg
660
- * October 27, 2008: Fixed up all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-6[this comment] with an exception of the final point by Ryan Bigg
661
- * October 26, 2008: Editing pass by link:../authors.html#mgunderloy[Mike Gunderloy] . First release version.
662
- * October 22, 2008: Calculations complete, first complete draft by Ryan Bigg
663
- * October 21, 2008: Extended named scope section by Ryan Bigg
664
- * October 9, 2008: Lock, count, cleanup by Ryan Bigg
665
- * October 6, 2008: Eager loading by Ryan Bigg
666
- * October 5, 2008: Covered conditions by Ryan Bigg
667
- * October 1, 2008: Covered limit/offset, formatting changes by Ryan Bigg
668
- * September 28, 2008: Covered first/last/all by Ryan Bigg