rails 2.1.2 → 2.2.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 (221) hide show
  1. data/CHANGELOG +27 -3
  2. data/Rakefile +70 -10
  3. data/bin/about +0 -0
  4. data/bin/console +0 -0
  5. data/bin/destroy +0 -0
  6. data/bin/generate +0 -0
  7. data/bin/performance/benchmarker +0 -0
  8. data/bin/performance/profiler +0 -0
  9. data/bin/performance/request +0 -0
  10. data/bin/plugin +0 -0
  11. data/bin/process/inspector +0 -0
  12. data/bin/process/reaper +0 -0
  13. data/bin/process/spawner +0 -0
  14. data/bin/runner +0 -0
  15. data/bin/server +0 -0
  16. data/config.ru +17 -0
  17. data/configs/apache.conf +0 -0
  18. data/configs/databases/ibm_db.yml +62 -0
  19. data/configs/databases/mysql.yml +3 -0
  20. data/configs/databases/postgresql.yml +3 -0
  21. data/configs/databases/sqlite2.yml +3 -0
  22. data/configs/databases/sqlite3.yml +3 -0
  23. data/configs/locales/en.yml +5 -0
  24. data/dispatches/dispatch.fcgi +1 -1
  25. data/dispatches/dispatch.rb +2 -2
  26. data/dispatches/gateway.cgi +2 -2
  27. data/doc/README_FOR_APP +5 -2
  28. data/doc/guides/html/2_2_release_notes.html +1185 -0
  29. data/doc/guides/html/actioncontroller_basics.html +1270 -0
  30. data/doc/guides/html/activerecord_validations_callbacks.html +749 -0
  31. data/doc/guides/html/association_basics.html +2585 -0
  32. data/doc/guides/html/authors.html +240 -0
  33. data/doc/guides/html/benchmarking_and_profiling.html +1018 -0
  34. data/doc/guides/html/caching_with_rails.html +583 -0
  35. data/doc/guides/html/command_line.html +434 -0
  36. data/doc/guides/html/configuring.html +438 -0
  37. data/doc/guides/html/creating_plugins.html +1594 -0
  38. data/doc/guides/html/debugging_rails_applications.html +1175 -0
  39. data/doc/guides/html/finders.html +1090 -0
  40. data/doc/guides/html/form_helpers.html +638 -0
  41. data/doc/guides/html/getting_started_with_rails.html +2066 -0
  42. data/doc/guides/html/index.html +349 -0
  43. data/doc/guides/html/layouts_and_rendering.html +1406 -0
  44. data/doc/guides/html/migrations.html +921 -0
  45. data/doc/guides/html/routing_outside_in.html +2213 -0
  46. data/doc/guides/html/security.html +1346 -0
  47. data/doc/guides/html/testing_rails_applications.html +1859 -0
  48. data/doc/guides/source/2_2_release_notes.txt +435 -0
  49. data/doc/guides/source/actioncontroller_basics/changelog.txt +5 -0
  50. data/doc/guides/source/actioncontroller_basics/cookies.txt +34 -0
  51. data/doc/guides/source/actioncontroller_basics/csrf.txt +32 -0
  52. data/doc/guides/source/actioncontroller_basics/filters.txt +119 -0
  53. data/doc/guides/source/actioncontroller_basics/http_auth.txt +24 -0
  54. data/doc/guides/source/actioncontroller_basics/index.txt +40 -0
  55. data/doc/guides/source/actioncontroller_basics/introduction.txt +9 -0
  56. data/doc/guides/source/actioncontroller_basics/methods.txt +39 -0
  57. data/doc/guides/source/actioncontroller_basics/parameter_filtering.txt +14 -0
  58. data/doc/guides/source/actioncontroller_basics/params.txt +93 -0
  59. data/doc/guides/source/actioncontroller_basics/request_response_objects.txt +43 -0
  60. data/doc/guides/source/actioncontroller_basics/rescue.txt +67 -0
  61. data/doc/guides/source/actioncontroller_basics/session.txt +187 -0
  62. data/doc/guides/source/actioncontroller_basics/streaming.txt +91 -0
  63. data/doc/guides/source/actioncontroller_basics/verification.txt +40 -0
  64. data/doc/guides/source/active_record_basics.txt +181 -0
  65. data/doc/guides/source/activerecord_validations_callbacks.txt +404 -0
  66. data/doc/guides/source/association_basics.txt +1840 -0
  67. data/doc/guides/source/authors.txt +39 -0
  68. data/doc/guides/source/benchmarking_and_profiling/appendix.txt +95 -0
  69. data/doc/guides/source/benchmarking_and_profiling/digging_deeper.txt +105 -0
  70. data/doc/guides/source/benchmarking_and_profiling/edge_rails_features.txt +185 -0
  71. data/doc/guides/source/benchmarking_and_profiling/gameplan.txt +27 -0
  72. data/doc/guides/source/benchmarking_and_profiling/index.txt +242 -0
  73. data/doc/guides/source/benchmarking_and_profiling/rubyprof.txt +179 -0
  74. data/doc/guides/source/benchmarking_and_profiling/statistics.txt +57 -0
  75. data/doc/guides/source/caching_with_rails.txt +367 -0
  76. data/doc/guides/source/command_line.txt +147 -0
  77. data/doc/guides/source/configuring.txt +225 -0
  78. data/doc/guides/source/creating_plugins/acts_as_yaffle.txt +191 -0
  79. data/doc/guides/source/creating_plugins/appendix.txt +46 -0
  80. data/doc/guides/source/creating_plugins/controllers.txt +59 -0
  81. data/doc/guides/source/creating_plugins/core_ext.txt +123 -0
  82. data/doc/guides/source/creating_plugins/custom_route.txt +69 -0
  83. data/doc/guides/source/creating_plugins/gem.txt +1 -0
  84. data/doc/guides/source/creating_plugins/generator_method.txt +89 -0
  85. data/doc/guides/source/creating_plugins/helpers.txt +51 -0
  86. data/doc/guides/source/creating_plugins/index.txt +52 -0
  87. data/doc/guides/source/creating_plugins/migration_generator.txt +156 -0
  88. data/doc/guides/source/creating_plugins/models.txt +76 -0
  89. data/doc/guides/source/creating_plugins/odds_and_ends.txt +69 -0
  90. data/doc/guides/source/creating_plugins/test_setup.txt +230 -0
  91. data/doc/guides/source/debugging_rails_applications.txt +733 -0
  92. data/doc/guides/source/finders.txt +668 -0
  93. data/doc/guides/source/form_helpers.txt +345 -0
  94. data/doc/guides/source/getting_started_with_rails.txt +1256 -0
  95. data/doc/guides/source/images/belongs_to.png +0 -0
  96. data/doc/guides/source/images/bullet.gif +0 -0
  97. data/doc/guides/source/images/csrf.png +0 -0
  98. data/doc/guides/source/images/habtm.png +0 -0
  99. data/doc/guides/source/images/has_many.png +0 -0
  100. data/doc/guides/source/images/has_many_through.png +0 -0
  101. data/doc/guides/source/images/has_one.png +0 -0
  102. data/doc/guides/source/images/has_one_through.png +0 -0
  103. data/doc/guides/source/images/header_backdrop.png +0 -0
  104. data/doc/guides/source/images/icons/README +5 -0
  105. data/doc/guides/source/images/icons/callouts/1.png +0 -0
  106. data/doc/guides/source/images/icons/callouts/10.png +0 -0
  107. data/doc/guides/source/images/icons/callouts/11.png +0 -0
  108. data/doc/guides/source/images/icons/callouts/12.png +0 -0
  109. data/doc/guides/source/images/icons/callouts/13.png +0 -0
  110. data/doc/guides/source/images/icons/callouts/14.png +0 -0
  111. data/doc/guides/source/images/icons/callouts/15.png +0 -0
  112. data/doc/guides/source/images/icons/callouts/2.png +0 -0
  113. data/doc/guides/source/images/icons/callouts/3.png +0 -0
  114. data/doc/guides/source/images/icons/callouts/4.png +0 -0
  115. data/doc/guides/source/images/icons/callouts/5.png +0 -0
  116. data/doc/guides/source/images/icons/callouts/6.png +0 -0
  117. data/doc/guides/source/images/icons/callouts/7.png +0 -0
  118. data/doc/guides/source/images/icons/callouts/8.png +0 -0
  119. data/doc/guides/source/images/icons/callouts/9.png +0 -0
  120. data/doc/guides/source/images/icons/caution.png +0 -0
  121. data/doc/guides/source/images/icons/example.png +0 -0
  122. data/doc/guides/source/images/icons/home.png +0 -0
  123. data/doc/guides/source/images/icons/important.png +0 -0
  124. data/doc/guides/source/images/icons/next.png +0 -0
  125. data/doc/guides/source/images/icons/note.png +0 -0
  126. data/doc/guides/source/images/icons/prev.png +0 -0
  127. data/doc/guides/source/images/icons/tip.png +0 -0
  128. data/doc/guides/source/images/icons/up.png +0 -0
  129. data/doc/guides/source/images/icons/warning.png +0 -0
  130. data/doc/guides/source/images/polymorphic.png +0 -0
  131. data/doc/guides/source/images/rails_logo_remix.gif +0 -0
  132. data/doc/guides/source/images/ruby_on_rails_by_mike_rundle2.gif +0 -0
  133. data/doc/guides/source/images/session_fixation.png +0 -0
  134. data/doc/guides/source/index.txt +118 -0
  135. data/doc/guides/source/layouts_and_rendering.txt +982 -0
  136. data/doc/guides/source/migrations/anatomy_of_a_migration.txt +85 -0
  137. data/doc/guides/source/migrations/changelog.txt +5 -0
  138. data/doc/guides/source/migrations/creating_a_migration.txt +109 -0
  139. data/doc/guides/source/migrations/foreign_keys.txt +8 -0
  140. data/doc/guides/source/migrations/index.txt +22 -0
  141. data/doc/guides/source/migrations/rakeing_around.txt +111 -0
  142. data/doc/guides/source/migrations/scheming.txt +47 -0
  143. data/doc/guides/source/migrations/using_models_in_migrations.txt +46 -0
  144. data/doc/guides/source/migrations/writing_a_migration.txt +159 -0
  145. data/doc/guides/source/routing_outside_in.txt +986 -0
  146. data/doc/guides/source/security.txt +984 -0
  147. data/doc/guides/source/stylesheets/base.css +358 -0
  148. data/doc/guides/source/stylesheets/forms.css +35 -0
  149. data/doc/guides/source/stylesheets/more.css +82 -0
  150. data/doc/guides/source/templates/guides.html.erb +97 -0
  151. data/doc/guides/source/templates/inline.css +165 -0
  152. data/doc/guides/source/testing_rails_applications.txt +995 -0
  153. data/environments/boot.rb +2 -2
  154. data/environments/environment.rb +9 -1
  155. data/environments/production.rb +3 -1
  156. data/helpers/performance_test.rb +9 -0
  157. data/html/500.html +4 -1
  158. data/html/javascripts/controls.js +72 -72
  159. data/html/javascripts/dragdrop.js +165 -164
  160. data/html/javascripts/effects.js +173 -165
  161. data/html/javascripts/prototype.js +362 -267
  162. data/lib/commands/console.rb +13 -0
  163. data/lib/commands/dbconsole.rb +2 -2
  164. data/lib/commands/ncgi/listener +2 -2
  165. data/lib/commands/ncgi/tracker +2 -2
  166. data/lib/commands/plugin.rb +41 -24
  167. data/lib/commands/process/spawner.rb +4 -4
  168. data/lib/commands/runner.rb +1 -1
  169. data/lib/commands/server.rb +11 -1
  170. data/lib/commands/servers/thin.rb +25 -0
  171. data/lib/fcgi_handler.rb +1 -3
  172. data/lib/initializer.rb +162 -39
  173. data/lib/performance_test_help.rb +5 -0
  174. data/lib/rails/gem_builder.rb +3 -3
  175. data/lib/rails/gem_dependency.rb +155 -33
  176. data/lib/rails/mongrel_server/commands.rb +1 -1
  177. data/lib/rails/plugin.rb +10 -2
  178. data/lib/rails/rack.rb +6 -0
  179. data/lib/rails/rack/logger.rb +28 -0
  180. data/lib/rails/rack/static.rb +35 -0
  181. data/lib/rails/vendor_gem_source_index.rb +140 -0
  182. data/lib/rails/version.rb +1 -1
  183. data/lib/rails_generator/commands.rb +10 -16
  184. data/lib/rails_generator/generated_attribute.rb +4 -0
  185. data/lib/rails_generator/generators/applications/app/app_generator.rb +9 -3
  186. data/lib/rails_generator/generators/components/controller/controller_generator.rb +1 -1
  187. data/lib/rails_generator/generators/components/controller/templates/functional_test.rb +1 -1
  188. data/lib/rails_generator/generators/components/integration_test/integration_test_generator.rb +1 -1
  189. data/lib/rails_generator/generators/components/integration_test/templates/integration_test.rb +2 -2
  190. data/lib/rails_generator/generators/components/mailer/mailer_generator.rb +1 -1
  191. data/lib/rails_generator/generators/components/mailer/templates/unit_test.rb +2 -3
  192. data/lib/rails_generator/generators/components/model/model_generator.rb +1 -1
  193. data/lib/rails_generator/generators/components/model/templates/model.rb +3 -0
  194. data/lib/rails_generator/generators/components/model/templates/unit_test.rb +1 -1
  195. data/lib/rails_generator/generators/components/observer/observer_generator.rb +1 -1
  196. data/lib/rails_generator/generators/components/observer/templates/unit_test.rb +1 -1
  197. data/lib/rails_generator/generators/components/performance_test/USAGE +8 -0
  198. data/lib/rails_generator/generators/components/performance_test/performance_test_generator.rb +16 -0
  199. data/lib/rails_generator/generators/components/performance_test/templates/performance_test.rb +9 -0
  200. data/lib/rails_generator/generators/components/plugin/plugin_generator.rb +11 -11
  201. data/lib/rails_generator/generators/components/plugin/templates/Rakefile +1 -0
  202. data/lib/rails_generator/generators/components/plugin/templates/test_helper.rb +3 -0
  203. data/lib/rails_generator/generators/components/plugin/templates/unit_test.rb +4 -4
  204. data/lib/rails_generator/generators/components/resource/resource_generator.rb +2 -2
  205. data/lib/rails_generator/generators/components/resource/templates/functional_test.rb +1 -1
  206. data/lib/rails_generator/generators/components/scaffold/USAGE +9 -5
  207. data/lib/rails_generator/generators/components/scaffold/scaffold_generator.rb +10 -3
  208. data/lib/rails_generator/generators/components/scaffold/templates/functional_test.rb +7 -7
  209. data/lib/rails_generator/scripts.rb +1 -1
  210. data/lib/rails_generator/scripts/destroy.rb +6 -7
  211. data/lib/rails_generator/secret_key_generator.rb +5 -147
  212. data/lib/tasks/annotations.rake +8 -11
  213. data/lib/tasks/databases.rake +42 -15
  214. data/lib/tasks/documentation.rake +15 -0
  215. data/lib/tasks/framework.rake +5 -1
  216. data/lib/tasks/gems.rake +24 -8
  217. data/lib/tasks/misc.rake +3 -4
  218. data/lib/tasks/testing.rake +25 -4
  219. data/lib/test_help.rb +1 -2
  220. data/lib/webrick_server.rb +2 -11
  221. metadata +165 -9
@@ -0,0 +1,85 @@
1
+ == Anatomy Of A Migration ==
2
+
3
+ Before I dive into the details of a migration, here are a few examples of the sorts of things you can do:
4
+
5
+ [source, ruby]
6
+ ------------------------
7
+ class CreateProducts < ActiveRecord::Migration
8
+ def self.up
9
+ create_table :products do |t|
10
+ t.string :name
11
+ t.text :description
12
+
13
+ t.timestamps
14
+ end
15
+ end
16
+
17
+ def self.down
18
+ drop_table :products
19
+ end
20
+ end
21
+ ------------------------
22
+
23
+ This migration adds a table called `products` with a string column called `name` and a text column called `description`. A primary key column called `id` will also be added, however since this is the default we do not need to ask for this. The timestamp columns `created_at` and `updated_at` which Active Record populates automatically will also be added. Reversing this migration is as simple as dropping the table.
24
+
25
+ Migrations are not limited to changing the schema. You can also use them to fix bad data in the database or populate new fields:
26
+
27
+ [source, ruby]
28
+ ------------------------
29
+ class AddReceiveNewsletterToUsers < ActiveRecord::Migration
30
+ def self.up
31
+ change_table :users do |t|
32
+ t.boolean :receive_newsletter, :default => false
33
+ end
34
+ User.update_all ["receive_newsletter = ?", true]
35
+ end
36
+
37
+ def self.down
38
+ remove_column :users, :receive_newsletter
39
+ end
40
+ end
41
+ ------------------------
42
+
43
+ This migration adds an `receive_newsletter` column to the `users` table. We want it to default to `false` for new users, but existing users are considered
44
+ to have already opted in, so we use the User model to set the flag to `true` for existing users.
45
+
46
+ NOTE: Some <<models,caveats>> apply to using models in your migrations.
47
+
48
+ === Migrations are classes
49
+ A migration is a subclass of ActiveRecord::Migration that implements two class methods: +up+ (perform the required transformations) and +down+ (revert them).
50
+
51
+ Active Record provides methods that perform common data definition tasks in a database independent way (you'll read about them in detail later):
52
+
53
+ * `create_table`
54
+ * `change_table`
55
+ * `drop_table`
56
+ * `add_column`
57
+ * `remove_column`
58
+ * `change_column`
59
+ * `rename_column`
60
+ * `add_index`
61
+ * `remove_index`
62
+
63
+ If you need to perform tasks specific to your database (for example create a <<foreign_key,foreign key>> constraint) then the `execute` function allows you to execute arbitrary SQL. A migration is just a regular Ruby class so you're not limited to these functions. For example after adding a column you could
64
+ write code to set the value of that column for existing records (if necessary using your models).
65
+
66
+ On databases that support transactions with statements that change the schema (such as PostgreSQL), migrations are wrapped in a transaction. If the database does not support this (for example MySQL and SQLite) then when a migration fails the parts of it that succeeded will not be rolled back. You will have to unpick the changes that were made by hand.
67
+
68
+ === What's in a name ===
69
+
70
+ Migrations are stored in files in `db/migrate`, one for each migration class. The name of the file is of the form `YYYYMMDDHHMMSS_create_products.rb`, that is to say a UTC timestamp identifying the migration followed by an underscore followed by the name of the migration. The migration class' name must match (the camelcased version of) the latter part of the file name. For example `20080906120000_create_products.rb` should define CreateProducts and `20080906120001_add_details_to_products.rb` should define AddDetailsToProducts. If you do feel the need to change the file name then you MUST update the name of the class inside or Rails will complain about a missing class.
71
+
72
+ Internally Rails only uses the migration's number (the timestamp) to identify them. Prior to Rails 2.1 the migration number started at 1 and was incremented each time a migration was generated. With multiple developers it was easy for these to clash requiring you to rollback migrations and renumber them. With Rails 2.1 this is largely avoided by using the creation time of the migration to identify them. You can revert to the old numbering scheme by setting `config.active_record.timestamped_migrations` to `false` in `environment.rb`.
73
+
74
+ The combination of timestamps and recording which migrations have been run allows Rails to handle common situations that occur with multiple developers.
75
+
76
+ For example Alice adds migrations `20080906120000` and `20080906123000` and Bob adds `20080906124500` and runs it. Alice finishes her changes and checks in her migrations and Bob pulls down the latest changes. Rails knows that it has not run Alice's two migrations so `rake db:migrate` would run them (even though Bob's migration with a later timestamp has been run), and similarly migrating down would not run their down methods.
77
+
78
+ Of course this is no substitution for communication within the team, for example if Alice's migration removed a table that Bob's migration assumed the existence of then trouble will still occur.
79
+
80
+ === Changing migrations ===
81
+
82
+ Occasionally you will make a mistake while writing a migration. If you have already run the migration then you cannot just edit the migration and run the migration again: Rails thinks it has already run the migration and so will do nothing when you run `rake db:migrate`. You must rollback the migration (for example with `rake db:rollback`), edit your migration and then run `rake db:migrate` to run the corrected version.
83
+
84
+ In general editing existing migrations is not a good idea: you will be creating extra work for yourself and your co-workers and cause major headaches if the existing version of the migration has already been run on production machines. Instead you should write a new migration that performs the changes you require. Editing a freshly generated migration that has not yet been committed to source control (or more generally which has not been propagated beyond your development machine) is relatively harmless. Just use some common sense.
85
+
@@ -0,0 +1,5 @@
1
+ == Changelog ==
2
+
3
+ http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/6[Lighthouse ticket]
4
+
5
+ * September 14, 2008: initial version by link:../authors.html#fcheung[Frederick Cheung]
@@ -0,0 +1,109 @@
1
+ == Creating A Migration ==
2
+
3
+ === Creating a model ===
4
+
5
+ The model and scaffold generators will create migrations appropriate for adding a new model. This migration will already contain instructions for creating the relevant table. If you tell Rails what columns you want then statements for adding those will also be created. For example, running
6
+
7
+ `ruby script/generate model Product name:string description:text` will create a migration that looks like this
8
+
9
+ [source, ruby]
10
+ -----------------------
11
+ class CreateProducts < ActiveRecord::Migration
12
+ def self.up
13
+ create_table :products do |t|
14
+ t.string :name
15
+ t.text :description
16
+
17
+ t.timestamps
18
+ end
19
+ end
20
+
21
+ def self.down
22
+ drop_table :products
23
+ end
24
+ end
25
+ -----------------------
26
+
27
+ You can append as many column name/type pairs as you want. By default `t.timestamps` (which creates the `updated_at` and `created_at` columns that
28
+ are automatically populated by Active Record) will be added for you.
29
+
30
+ === Creating a standalone migration ===
31
+ If you are creating migrations for other purposes (for example to add a column to an existing table) then you can use the migration generator:
32
+
33
+ `ruby script/generate migration AddPartNumberToProducts`
34
+
35
+ This will create an empty but appropriately named migration:
36
+
37
+ [source, ruby]
38
+ -----------------------
39
+ class AddPartNumberToProducts < ActiveRecord::Migration
40
+ def self.up
41
+ end
42
+
43
+ def self.down
44
+ end
45
+ end
46
+ -----------------------
47
+
48
+ If the migration name is of the form AddXXXToYYY or RemoveXXXFromY and is followed by a list of column names and types then a migration containing
49
+ the appropriate add and remove column statements will be created.
50
+
51
+ `ruby script/generate migration AddPartNumberToProducts part_number:string`
52
+
53
+ will generate
54
+
55
+ [source, ruby]
56
+ -----------------------
57
+ class AddPartNumberToProducts < ActiveRecord::Migration
58
+ def self.up
59
+ add_column :products, :part_number, :string
60
+ end
61
+
62
+ def self.down
63
+ remove_column :products, :part_number
64
+ end
65
+ end
66
+ -----------------------
67
+
68
+ Similarly,
69
+
70
+ `ruby script/generate migration RemovePartNumberFromProducts part_number:string`
71
+
72
+ generates
73
+
74
+ [source, ruby]
75
+ -----------------------
76
+ class RemovePartNumberFromProducts < ActiveRecord::Migration
77
+ def self.up
78
+ remove_column :products, :part_number
79
+ end
80
+
81
+ def self.down
82
+ add_column :products, :part_number, :string
83
+ end
84
+ end
85
+ -----------------------
86
+
87
+ You are not limited to one magically generated column, for example
88
+
89
+ `ruby script/generate migration AddDetailsToProducts part_number:string price:decimal`
90
+
91
+ generates
92
+
93
+ [source, ruby]
94
+ -----------------------
95
+ class AddDetailsToProducts < ActiveRecord::Migration
96
+ def self.up
97
+ add_column :products, :part_number, :string
98
+ add_column :products, :price, :decimal
99
+ end
100
+
101
+ def self.down
102
+ remove_column :products, :price
103
+ remove_column :products, :part_number
104
+ end
105
+ end
106
+ -----------------------
107
+
108
+ As always, what has been generated for you is just a starting point. You can add or remove from it as you see fit.
109
+
@@ -0,0 +1,8 @@
1
+ [[foreign_key]]
2
+ == Active Record and Referential Integrity ==
3
+ The Active Record way is that intelligence belongs in your models, not in the database. As such, features such as triggers or foreign key constraints, which push some of that intelligence back into the database are not heavily used.
4
+
5
+ Validations such as `validates_uniqueness_of` are one way in which models can enforce data integrity. The `:dependent` option on associations allows models to automatically destroy child objects when the parent is destroyed. Like anything which operates at the application level these cannot guarantee referential integrity and so some people augment them with foreign key constraints.
6
+
7
+ Although Active Record does not provide any tools for working directly with such features, the `execute` method can be used to execute arbitrary SQL. There are also a number of plugins such as http://agilewebdevelopment.com/plugins/search?search=redhillonrails[redhillonrails] which add foreign key support to Active Record (including support for dumping foreign keys in `schema.rb`).
8
+
@@ -0,0 +1,22 @@
1
+ Migrations
2
+ ==========
3
+
4
+ Migrations are a convenient way for you to alter your database in a structured and organised manner. You could edit fragments of SQL by hand but you would then be responsible for telling other developers that they need to go and run it. You'd also have to keep track of which changes need to be run against the production machines next time you deploy. Active Record tracks which migrations have already been run so all you have to do is update your source and run `rake db:migrate`. Active Record will work out which migrations should be run.
5
+
6
+ Migrations also allow you to describe these transformations using Ruby. The great thing about this is that (like most of Active Record's functionality) it is database independent: you don't need to worry about the precise syntax of CREATE TABLE any more that you worry about variations on SELECT * (you can drop down to raw SQL for database specific features). For example you could use SQLite3 in development, but MySQL in production.
7
+
8
+ You'll learn all about migrations including:
9
+
10
+ * The generators you can use to create them
11
+ * The methods Active Record provides to manipulate your database
12
+ * The Rake tasks that manipulate them
13
+ * How they relate to `schema.rb`
14
+
15
+ include::anatomy_of_a_migration.txt[]
16
+ include::creating_a_migration.txt[]
17
+ include::writing_a_migration.txt[]
18
+ include::rakeing_around.txt[]
19
+ include::using_models_in_migrations.txt[]
20
+ include::scheming.txt[]
21
+ include::foreign_keys.txt[]
22
+ include::changelog.txt[]
@@ -0,0 +1,111 @@
1
+ == Running Migrations ==
2
+
3
+ Rails provides a set of rake tasks to work with migrations which boils down to running certain sets of migrations. The very first migration related rake task you use will probably be `db:migrate`. In its most basic form it just runs the `up` method for all the migrations that have not yet been run. If there are no such migrations it exits.
4
+
5
+ If you specify a target version, Active Record will run the required migrations (up or down) until it has reached the specified version. The
6
+ version is the numerical prefix on the migration's filename. For example to migrate to version 20080906120000 run
7
+
8
+ ------------------------------------
9
+ rake db:migrate VERSION=20080906120000
10
+ ------------------------------------
11
+
12
+ If this is greater than the current version (i.e. it is migrating upwards) this will run the `up` method on all migrations up to and including 20080906120000, if migrating downwards this will run the `down` method on all the migrations down to, but not including, 20080906120000.
13
+
14
+ === Rolling back ===
15
+
16
+ A common task is to rollback the last migration, for example if you made a mistake in it and wish to correct it. Rather than tracking down the version number associated with the previous migration you can run
17
+
18
+ ------------------
19
+ rake db:rollback
20
+ ------------------
21
+
22
+ This will run the `down` method from the latest migration. If you need to undo several migrations you can provide a `STEP` parameter:
23
+
24
+ ------------------
25
+ rake db:rollback STEP=3
26
+ ------------------
27
+
28
+ will run the `down` method from the last 3 migrations.
29
+
30
+ The `db:migrate:redo` task is a shortcut for doing a rollback and then migrating back up again. As with the `db:rollback` task you can use the `STEP` parameter if you need to go more than one version back, for example
31
+
32
+ ------------------
33
+ rake db:migrate:redo STEP=3
34
+ ------------------
35
+
36
+ Neither of these Rake tasks do anything you could not do with `db:migrate`, they are simply more convenient since you do not need to explicitly specify the version to migrate to.
37
+
38
+ Lastly, the `db:reset` task will drop the database, recreate it and load the current schema into it.
39
+
40
+ NOTE: This is not the same as running all the migrations - see the section on <<schema,schema.rb>>.
41
+
42
+ === Being Specific ===
43
+
44
+ If you need to run a specific migration up or down the `db:migrate:up` and `db:migrate:down` tasks will do that. Just specify the appropriate version and the corresponding migration will have its `up` or `down` method invoked, for example
45
+
46
+ ------------------
47
+ rake db:migrate:up VERSION=20080906120000
48
+ ------------------
49
+
50
+ will run the `up` method from the 20080906120000 migration. These tasks check whether the migration has already run, so for example `db:migrate:up VERSION=20080906120000` will do nothing if Active Record believes that 20080906120000 has already been run.
51
+
52
+
53
+ === Being talkative ===
54
+
55
+ By default migrations tell you exactly what they're doing and how long it took.
56
+ A migration creating a table and adding an index might produce output like this
57
+ -------------------------
58
+ == 20080906170109 CreateProducts: migrating ===================================
59
+ -- create_table(:products)
60
+ -> 0.0021s
61
+ -- add_index(:products, :name)
62
+ -> 0.0026s
63
+ == 20080906170109 CreateProducts: migrated (0.0059s) ==========================
64
+ -------------------------
65
+ Several methods are provided that allow you to control all this:
66
+
67
+ * `suppress_messages` suppresses any output generated by its block
68
+ * `say` outputs text (the second argument controls whether it is indented or not)
69
+ * `say_with_time` outputs text along with how long it took to run its block. If the block returns an integer it assumes it is the number of rows affected.
70
+
71
+ For example, this migration
72
+
73
+ [source, ruby]
74
+ ----------------------
75
+ class CreateProducts < ActiveRecord::Migration
76
+ def self.up
77
+ suppress_messages do
78
+ create_table :products do |t|
79
+ t.string :name
80
+ t.text :description
81
+ t.timestamps
82
+ end
83
+ end
84
+ say "Created a table"
85
+ suppress_messages {add_index :products, :name}
86
+ say "and an index!", true
87
+ say_with_time 'Waiting for a while' do
88
+ sleep 10
89
+ 250
90
+ end
91
+ end
92
+
93
+ def self.down
94
+ drop_table :products
95
+ end
96
+ end
97
+ ----------------------
98
+
99
+ generates the following output
100
+ ----------------------
101
+ == 20080906170109 CreateProducts: migrating ===================================
102
+ -- Created a table
103
+ -> and an index!
104
+ -- Waiting for a while
105
+ -> 10.0001s
106
+ -> 250 rows
107
+ == 20080906170109 CreateProducts: migrated (10.0097s) =========================
108
+ ----------------------
109
+
110
+ If you just want Active Record to shut up then running `rake db:migrate VERBOSE=false` will suppress any output.
111
+
@@ -0,0 +1,47 @@
1
+ == Schema dumping and you ==
2
+ [[schema]]
3
+ === What are schema files for? ===
4
+ Migrations, mighty as they may be, are not the authoritative source for your database schema. That role falls to either `schema.rb` or an SQL file which Active Record generates by examining the database. They are not designed to be edited, they just represent the current state of the database.
5
+
6
+ There is no need (and it is error prone) to deploy a new instance of an app by replaying the entire migration history. It is much simpler and faster to just load into the database a description of the current schema.
7
+
8
+ For example, this is how the test database is created: the current development database is dumped (either to `schema.rb` or `development.sql`) and then loaded into the test database.
9
+
10
+ Schema files are also useful if you want a quick look at what attributes an Active Record object has. This information is not in the model's code and is frequently spread across several migrations but is all summed up in the schema file. The http://agilewebdevelopment.com/plugins/annotate_models[annotate_models] plugin, which automatically adds (and updates) comments at the top of each model summarising the schema, may also be of interest.
11
+
12
+ === Types of schema dumps ===
13
+ There are two ways to dump the schema. This is set in `config/environment.rb` by the `config.active_record.schema_format` setting, which may be either `:sql` or `:ruby`.
14
+
15
+ If `:ruby` is selected then the schema is stored in `db/schema.rb`. If you look at this file you'll find that it looks an awful lot like one very big migration:
16
+
17
+ [source, ruby]
18
+ --------------------------------------
19
+ ActiveRecord::Schema.define(:version => 20080906171750) do
20
+ create_table "authors", :force => true do |t|
21
+ t.string "name"
22
+ t.datetime "created_at"
23
+ t.datetime "updated_at"
24
+ end
25
+
26
+ create_table "products", :force => true do |t|
27
+ t.string "name"
28
+ t.text "description"
29
+ t.datetime "created_at"
30
+ t.datetime "updated_at"
31
+ t.string "part_number"
32
+ end
33
+ end
34
+ --------------------------------------
35
+
36
+ In many ways this is exactly what it is. This file is created by inspecting the database and expressing its structure using `create_table`, `add_index` and so on. Because this is database independent it could be loaded into any database that Active Record supports. This could be very useful if you were to distribute an application that is able to run against multiple databases.
37
+
38
+ There is however a trade-off: `schema.rb` cannot express database specific items such as foreign key constraints, triggers or stored procedures. While in a migration you can execute custom SQL statements, the schema dumper cannot reconstitute those statements from the database. If you are using features like this then you should set the schema format to `:sql`.
39
+
40
+ Instead of using Active Record's schema dumper the database's structure will be dumped using a tool specific to that database (via the `db:structure:dump` Rake task) into `db/#\{RAILS_ENV\}_structure.sql`. For example for PostgreSQL the `pg_dump` utility is used and for MySQL this file will contain the output of SHOW CREATE TABLE for the various tables. Loading this schema is simply a question of executing the SQL statements contained inside.
41
+
42
+ By definition this will be a perfect copy of the database's structure but this will usually prevent loading the schema into a database other than the one used to create it.
43
+
44
+ === Schema dumps and source control ===
45
+
46
+ Because they are the authoritative source for your database schema, it is strongly recommended that you check them into source control.
47
+
@@ -0,0 +1,46 @@
1
+ [[models]]
2
+ == Using Models In Your Migrations ==
3
+ When creating or updating data in a migration it is often tempting to use one of your models. After all they exist to provide easy access to the underlying data. This can be done but some caution should be observed.
4
+
5
+ Consider for example a migration that uses the Product model to update a row in the corresponding table. Alice later updates the Product model, adding a new column and a validation on it. Bob comes back from holiday, updates the source and runs outstanding migrations with `rake db:migrate`, including the one that used the Product model. When the migration runs the source is up to date and so the Product model has the validation added by Alice. The database however is still old and so does not have that column and an error ensues because that validation is on a column that does not yet exist.
6
+
7
+ Frequently I just want to update rows in the database without writing out the SQL by hand: I'm not using anything specific to the model. One pattern for this is to define a copy of the model inside the migration itself, for example:
8
+
9
+ [source, ruby]
10
+ -------------------------
11
+ class AddPartNumberToProducts < ActiveRecord::Migration
12
+ class Product < ActiveRecord::Base
13
+ end
14
+
15
+ def self.up
16
+ ...
17
+ end
18
+
19
+ def self.down
20
+ ...
21
+ end
22
+ end
23
+ -------------------------
24
+ The migration has its own minimal copy of the Product model and no longer cares about the Product model defined in the application.
25
+
26
+ === Dealing with changing models ===
27
+
28
+ For performance reasons information about the columns a model has is cached. For example if you add a column to a table and then try and use the corresponding model to insert a new row it may try and use the old column information. You can force Active Record to re-read the column information with the `reset_column_information` method, for example
29
+
30
+ [source, ruby]
31
+ -------------------------
32
+ class AddPartNumberToProducts < ActiveRecord::Migration
33
+ class Product < ActiveRecord::Base
34
+ end
35
+
36
+ def self.up
37
+ add_column :product, :part_number, :string
38
+ Product.reset_column_information
39
+ ...
40
+ end
41
+
42
+ def self.down
43
+ ...
44
+ end
45
+ end
46
+ -------------------------
@@ -0,0 +1,159 @@
1
+ == Writing a Migration ==
2
+
3
+ Once you have created your migration using one of the generators it's time to get to work!
4
+
5
+ === Creating a table ===
6
+
7
+ `create_table` will be one of your workhorses. A typical use would be
8
+
9
+ [source, ruby]
10
+ ---------------------
11
+ create_table :products do |t|
12
+ t.string :name
13
+ end
14
+ ---------------------
15
+ which creates a `products` table with a column called `name` (and as discussed below, an implicit `id` column).
16
+
17
+ The object yielded to the block allows you create columns on the table. There are two ways of doing this. The first looks like
18
+
19
+ [source, ruby]
20
+ ---------------------
21
+ create_table :products do |t|
22
+ t.column :name, :string, :null => false
23
+ end
24
+ ---------------------
25
+
26
+ the second form, the so called "sexy" migrations, drops the somewhat redundant column method. Instead, the `string`, `integer` etc. methods create a column of that type. Subsequent parameters are identical.
27
+
28
+ [source, ruby]
29
+ ---------------------
30
+ create_table :products do |t|
31
+ t.string :name, :null => false
32
+ end
33
+ ---------------------
34
+
35
+ By default `create_table` will create a primary key called `id`. You can change the name of the primary key with the `:primary_key` option (don't forget to update the corresponding model) or if you don't want a primary key at all (for example for a HABTM join table) you can pass `:id => false`. If you need to pass database specific options you can place an sql fragment in the `:options` option. For example
36
+
37
+ [source, ruby]
38
+ ---------------------
39
+ create_table :products, :options => "ENGINE=BLACKHOLE" do |t|
40
+ t.string :name, :null => false
41
+ end
42
+ ---------------------
43
+ Will append `ENGINE=BLACKHOLE` to the sql used to create the table (when using MySQL the default is "ENGINE=InnoDB").
44
+
45
+ The types Active Record supports are `:primary_key`, `:string`, `:text`, `:integer`, `:float`, `:decimal`, `:datetime`, `:timestamp`, `:time`, `:date`, `:binary`, `:boolean`.
46
+
47
+ These will be mapped onto an appropriate underlying database type, for example with MySQL `:string` is mapped to `VARCHAR(255)`. You can create columns of
48
+ types not supported by Active Record when using the non sexy syntax, for example
49
+
50
+ [source, ruby]
51
+ ---------------------
52
+ create_table :products do |t|
53
+ t.column :name, 'polygon', :null => false
54
+ end
55
+ ---------------------
56
+ This may however hinder portability to other databases.
57
+
58
+ === Changing tables ===
59
+
60
+ `create_table`'s close cousin is `change_table`. Used for changing existing tables, it is used in a similar fashion to `create_table` but the object yielded to the block knows more tricks. For example
61
+
62
+ [source, ruby]
63
+ ---------------------
64
+ change_table :products do |t|
65
+ t.remove :description, :name
66
+ t.string :part_number
67
+ t.index :part_number
68
+ t.rename :upccode, :upc_code
69
+ end
70
+ ---------------------
71
+ removes the `description` column, creates a `part_number` column and adds an index on it. Finally it renames the `upccode` column. This is the same as doing
72
+
73
+ [source, ruby]
74
+ ---------------------
75
+ remove_column :products, :description
76
+ remove_column :products, :name
77
+ add_column :products, :part_number, :string
78
+ add_index :products, :part_number
79
+ rename_column :products, :upccode, :upc_code
80
+ ---------------------
81
+
82
+ You don't have to keep repeating the table name and it groups all the statements related to modifying one particular table. The individual transformation names are also shorter, for example `remove_column` becomes just `remove` and `add_index` becomes just `index`.
83
+
84
+ === Special helpers ===
85
+
86
+ Active Record provides some shortcuts for common functionality. It is for example very common to add both the `created_at` and `updated_at` columns and so there is a method that does exactly that:
87
+
88
+ [source, ruby]
89
+ ---------------------
90
+ create_table :products do |t|
91
+ t.timestamps
92
+ end
93
+ ---------------------
94
+ will create a new products table with those two columns whereas
95
+
96
+ [source, ruby]
97
+ ---------------------
98
+ change_table :products do |t|
99
+ t.timestamps
100
+ end
101
+ ---------------------
102
+ adds those columns to an existing table.
103
+
104
+ The other helper is called `references` (also available as `belongs_to`). In its simplest form it just adds some readability
105
+
106
+ [source, ruby]
107
+ ---------------------
108
+ create_table :products do |t|
109
+ t.references :category
110
+ end
111
+ ---------------------
112
+
113
+ will create a `category_id` column of the appropriate type. Note that you pass the model name, not the column name. Active Record adds the `_id` for you. If you have polymorphic belongs_to associations then `references` will add both of the columns required:
114
+
115
+ [source, ruby]
116
+ ---------------------
117
+ create_table :products do |t|
118
+ t.references :attachment, :polymorphic => {:default => 'Photo'}
119
+ end
120
+ ---------------------
121
+ will add an `attachment_id` column and a string `attachment_type` column with a default value of 'Photo'.
122
+
123
+ NOTE: The `references` helper does not actually create foreign key constraints for you. You will need to use `execute` for that or a plugin that adds <<foreign_key,foreign key support>>.
124
+
125
+ If the helpers provided by Active Record aren't enough you can use the `execute` function to execute arbitrary SQL.
126
+
127
+ For more details and examples of individual methods check the API documentation, in particular the documentation for http://api.rubyonrails.com/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html[ActiveRecord::ConnectionAdapters::SchemaStatements] (which provides the methods available in the `up` and `down` methods), http://api.rubyonrails.com/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html[ActiveRecord::ConnectionAdapters::TableDefinition] (which provides the methods available on the object yielded by `create_table`) and http://api.rubyonrails.com/classes/ActiveRecord/ConnectionAdapters/Table.html[ActiveRecord::ConnectionAdapters::Table] (which provides the methods available on the object yielded by `change_table`).
128
+
129
+ === Writing your down method ===
130
+
131
+ The `down` method of your migration should revert the transformations done by the `up` method. In other words the database should be unchanged if you do an `up` followed by a `down`. For example if you create a table in the up you should drop it in the `down` method. It is wise to do things in precisely the reverse order to in the `up` method. For example
132
+
133
+ [source, ruby]
134
+ ---------------------
135
+ class ExampleMigration < ActiveRecord::Migration
136
+
137
+ def self.up
138
+ create_table :products do |t|
139
+ t.references :category
140
+ end
141
+ #add a foreign key
142
+ execute "ALTER TABLE products ADD CONSTRAINT fk_products_categories FOREIGN KEY (category_id) REFERENCES categories(id)"
143
+
144
+ add_column :users, :home_page_url, :string
145
+
146
+ rename_column :users, :email, :email_address
147
+ end
148
+
149
+ def self.down
150
+ rename_column :users, :email_address, :email
151
+ remove_column :users, :home_page_url
152
+ execute "ALTER TABLE products DROP FOREIGN KEY fk_products_categories"
153
+ drop_table :products
154
+ end
155
+ end
156
+ ---------------------
157
+ Sometimes your migration will do something which is just plain irreversible, for example it might destroy some data. In cases like those when you can't reverse the migration you can raise IrreversibleMigration from your `down` method. If someone tries to revert your migration an error message will be
158
+ displayed saying that it can't be done.
159
+