railties 3.0.0.beta3 → 3.0.0.beta4

Sign up to get free protection for your applications and to get access to all the features.
Files changed (93) hide show
  1. data/CHANGELOG +5 -0
  2. data/README +118 -123
  3. data/guides/source/3_0_release_notes.textile +13 -11
  4. data/guides/source/action_controller_overview.textile +2 -2
  5. data/guides/source/action_mailer_basics.textile +70 -26
  6. data/guides/source/action_view_overview.textile +1 -1
  7. data/guides/source/active_record_basics.textile +9 -1
  8. data/guides/source/active_record_querying.textile +2 -2
  9. data/guides/source/active_support_core_extensions.textile +377 -9
  10. data/guides/source/activerecord_validations_callbacks.textile +98 -55
  11. data/guides/source/association_basics.textile +1 -1
  12. data/guides/source/caching_with_rails.textile +1 -1
  13. data/guides/source/command_line.textile +23 -23
  14. data/guides/source/configuring.textile +1 -3
  15. data/guides/source/contribute.textile +27 -28
  16. data/guides/source/credits.html.erb +4 -4
  17. data/guides/source/debugging_rails_applications.textile +2 -2
  18. data/guides/source/form_helpers.textile +7 -6
  19. data/guides/source/generators.textile +19 -29
  20. data/guides/source/getting_started.textile +106 -49
  21. data/guides/source/i18n.textile +27 -27
  22. data/guides/source/index.html.erb +18 -8
  23. data/guides/source/initialization.textile +140 -514
  24. data/guides/source/layout.html.erb +6 -4
  25. data/guides/source/layouts_and_rendering.textile +5 -5
  26. data/guides/source/migrations.textile +7 -3
  27. data/guides/source/nested_model_forms.textile +2 -2
  28. data/guides/source/performance_testing.textile +11 -12
  29. data/guides/source/plugins.textile +30 -30
  30. data/guides/source/rails_application_templates.textile +3 -3
  31. data/guides/source/rails_on_rack.textile +3 -66
  32. data/guides/source/routing.textile +10 -4
  33. data/guides/source/security.textile +1 -1
  34. data/guides/source/testing.textile +55 -52
  35. data/guides/w3c_validator.rb +67 -0
  36. data/lib/rails.rb +1 -0
  37. data/lib/rails/application.rb +49 -13
  38. data/lib/rails/application/bootstrap.rb +7 -6
  39. data/lib/rails/application/configuration.rb +24 -47
  40. data/lib/rails/application/finisher.rb +8 -3
  41. data/lib/rails/backtrace_cleaner.rb +11 -12
  42. data/lib/rails/commands.rb +54 -54
  43. data/lib/rails/commands/application.rb +7 -2
  44. data/lib/rails/commands/{performance/benchmarker.rb → benchmarker.rb} +0 -0
  45. data/lib/rails/commands/dbconsole.rb +4 -3
  46. data/lib/rails/commands/destroy.rb +1 -0
  47. data/lib/rails/commands/generate.rb +1 -0
  48. data/lib/rails/commands/{performance/profiler.rb → profiler.rb} +0 -0
  49. data/lib/rails/commands/runner.rb +4 -2
  50. data/lib/rails/configuration.rb +36 -0
  51. data/lib/rails/engine.rb +24 -24
  52. data/lib/rails/engine/configuration.rb +0 -1
  53. data/lib/rails/generators.rb +48 -10
  54. data/lib/rails/generators/actions.rb +5 -3
  55. data/lib/rails/generators/base.rb +23 -17
  56. data/lib/rails/generators/erb/scaffold/templates/_form.html.erb +9 -8
  57. data/lib/rails/generators/erb/scaffold/templates/show.html.erb +1 -1
  58. data/lib/rails/generators/generated_attribute.rb +7 -6
  59. data/lib/rails/generators/rails/app/USAGE +2 -2
  60. data/lib/rails/generators/rails/app/app_generator.rb +242 -97
  61. data/lib/rails/generators/rails/app/templates/Gemfile +3 -0
  62. data/lib/rails/generators/rails/app/templates/README +167 -130
  63. data/lib/rails/generators/rails/app/templates/Rakefile +0 -3
  64. data/lib/rails/generators/rails/app/templates/config/boot.rb +9 -2
  65. data/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml +5 -5
  66. data/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt +4 -0
  67. data/lib/rails/generators/rails/app/templates/script/rails +2 -5
  68. data/lib/rails/generators/rails/generator/templates/%file_name%_generator.rb.tt +1 -3
  69. data/lib/rails/generators/rails/stylesheets/templates/scaffold.css +5 -9
  70. data/lib/rails/generators/test_case.rb +12 -0
  71. data/lib/rails/generators/test_unit/integration/templates/integration_test.rb +1 -1
  72. data/lib/rails/generators/test_unit/performance/templates/performance_test.rb +1 -1
  73. data/lib/rails/info.rb +0 -33
  74. data/lib/rails/log_subscriber.rb +13 -6
  75. data/lib/rails/rack/logger.rb +4 -3
  76. data/lib/rails/railtie.rb +4 -0
  77. data/lib/rails/railtie/configuration.rb +21 -4
  78. data/lib/rails/tasks/documentation.rake +2 -0
  79. data/lib/rails/tasks/framework.rake +22 -0
  80. data/lib/rails/tasks/middleware.rake +1 -1
  81. data/lib/rails/tasks/routes.rake +5 -1
  82. data/lib/rails/test_help.rb +3 -1
  83. data/lib/rails/test_unit/testing.rake +3 -1
  84. data/lib/rails/version.rb +1 -1
  85. metadata +12 -19
  86. data/lib/rails/application/metal_loader.rb +0 -50
  87. data/lib/rails/dispatcher.rb +0 -24
  88. data/lib/rails/generators/rails/mailer/USAGE +0 -15
  89. data/lib/rails/generators/rails/mailer/mailer_generator.rb +0 -14
  90. data/lib/rails/generators/rails/mailer/templates/mailer.rb +0 -16
  91. data/lib/rails/generators/rails/metal/USAGE +0 -8
  92. data/lib/rails/generators/rails/metal/metal_generator.rb +0 -11
  93. data/lib/rails/generators/rails/metal/templates/metal.rb +0 -12
@@ -43,6 +43,10 @@ Ruby on Rails Guides: Credits
43
43
  Jeff Dean is a software engineer with <a href="http://pivotallabs.com">Pivotal Labs</a>.
44
44
  <% end %>
45
45
 
46
+ <%= author('Mikel Lindsaar', 'raasdnil') do %>
47
+ Mikel Lindsaar has been working with Rails since 2006 and is the author of the Ruby <a href="http://github.com/mikel/mail">Mail gem</a> and core contributor (he helped re-write Action Mailer's API). Mikel is the founder of <a href="http://rubyx.com/">RubyX</a>, has a <a href="http://lindsaar.net/">blog</a> and <a href="http://twitter.com/raasdnil">tweets</a>.
48
+ <% end %>
49
+
46
50
  <%= author('Cássio Marques', 'cmarques') do %>
47
51
  Cássio Marques is a Brazilian software developer working with different programming languages such as Ruby, JavaScript, CPP and Java, as an independent consultant. He blogs at <a href="http://cassiomarques.wordpress.com">/* CODIFICANDO */</a>, which is mainly written in Portuguese, but will soon get a new section for posts with English translation.
48
52
  <% end %>
@@ -58,7 +62,3 @@ Ruby on Rails Guides: Credits
58
62
  <%= author('Heiko Webers', 'hawe') do %>
59
63
  Heiko Webers is the founder of <a href="http://www.bauland42.de">bauland42</a>, a German web application security consulting and development company focused on Ruby on Rails. He blogs at the <a href="http://www.rorsecurity.info">Ruby on Rails Security Project</a>. After 10 years of desktop application development, Heiko has rarely looked back.
60
64
  <% end %>
61
-
62
- <%= author('Mikel Lindsaar', 'raasdnil') do %>
63
- Mikel Lindsaar has been working with Rails since 2006 and is the author of the Ruby Mail gem and core contributor (he helped re-write Action Mailer's API). Mikel has a <a href="http://lindsaar.net/">blog</a> and <a href="http://twitter.com/raasdnil">tweets</a>.
64
- <% end %>
@@ -136,7 +136,7 @@ config.logger = Logger.new(STDOUT)
136
136
  config.logger = Log4r::Logger.new("Application Log")
137
137
  </ruby>
138
138
 
139
- TIP: By default, each log is created under +RAILS_ROOT/log/+ and the log file name is +environment_name.log+.
139
+ TIP: By default, each log is created under +Rails.root/log/+ and the log file name is +environment_name.log+.
140
140
 
141
141
  h4. Log Levels
142
142
 
@@ -680,7 +680,7 @@ h3. Plugins for Debugging
680
680
 
681
681
  There are some Rails plugins to help you to find errors and debug your application. Here is a list of useful plugins for debugging:
682
682
 
683
- * "Footnotes":http://github.com/drnic/rails-footnotes/tree/master: Every Rails page has footnotes that give request information and link back to your source via TextMate.
683
+ * "Footnotes":http://github.com/josevalim/rails-footnotes: Every Rails page has footnotes that give request information and link back to your source via TextMate.
684
684
  * "Query Trace":http://github.com/ntalbott/query_trace/tree/master: Adds query origin tracing to your logs.
685
685
  * "Query Stats":http://github.com/dan-manges/query_stats/tree/master: A Rails plugin to track database queries.
686
686
  * "Query Reviewer":http://code.google.com/p/query-reviewer/: This rails plugin not only runs "EXPLAIN" before each of your select queries in development, but provides a small DIV in the rendered output of each page with the summary of warnings for each query that it analyzed.
@@ -205,7 +205,7 @@ Upon form submission the value entered by the user will be stored in +params[:pe
205
205
 
206
206
  WARNING: You must pass the name of an instance variable, i.e. +:person+ or +"person"+, not an actual instance of your model object.
207
207
 
208
- Rails provides helpers for displaying the validation errors associated with a model object. These are covered in detail by the "Active Record Validations and Callbacks":./activerecord_validations_callbacks.html#_using_the_tt_errors_tt_collection_in_your_view_templates guide.
208
+ Rails provides helpers for displaying the validation errors associated with a model object. These are covered in detail by the "Active Record Validations and Callbacks":./activerecord_validations_callbacks.html#displaying-validation-errors-in-the-view guide.
209
209
 
210
210
  h4. Binding a Form to an Object
211
211
 
@@ -255,7 +255,7 @@ You can create a similar binding without actually creating +&lt;form&gt;+ tags
255
255
  <erb>
256
256
  <%= form_for :person, @person, :url => { :action => "create" } do |person_form| %>
257
257
  <%= person_form.text_field :name %>
258
- <% fields_for @person.contact_detail do |contact_details_form| %>
258
+ <%= fields_for @person.contact_detail do |contact_details_form| %>
259
259
  <%= contact_details_form.text_field :phone_number %>
260
260
  <% end %>
261
261
  <% end %>
@@ -280,7 +280,7 @@ The Article model is directly available to users of the application, so -- follo
280
280
  map.resources :articles
281
281
  </ruby>
282
282
 
283
- TIP: Declaring a resource has a number of side-affects. See "Rails Routing From the Outside In":routing.html#restful-routing-the-rails-default for more information on setting up and using resources.
283
+ TIP: Declaring a resource has a number of side-affects. See "Rails Routing From the Outside In":routing.html#resource-routing-the-rails-default for more information on setting up and using resources.
284
284
 
285
285
  When dealing with RESTful resources, calls to +form_for+ can get significantly easier if you rely on *record identification*. In short, you can just pass the model instance and have Rails figure out model name and the rest:
286
286
 
@@ -697,7 +697,7 @@ You might want to render a form with a set of edit fields for each of a person's
697
697
  <%= form_for @person do |person_form| %>
698
698
  <%= person_form.text_field :name %>
699
699
  <% for address in @person.addresses %>
700
- <% person_form.fields_for address, :index => address do |address_form|%>
700
+ <%= person_form.fields_for address, :index => address do |address_form|%>
701
701
  <%= address_form.text_field :city %>
702
702
  <% end %>
703
703
  <% end %>
@@ -725,7 +725,7 @@ Rails knows that all these inputs should be part of the person hash because you
725
725
  To create more intricate nestings, you can specify the first part of the input name (+person[address]+ in the previous example) explicitly, for example
726
726
 
727
727
  <erb>
728
- <% fields_for 'person[address][primary]', address, :index => address do |address_form| %>
728
+ <%= fields_for 'person[address][primary]', address, :index => address do |address_form| %>
729
729
  <%= address_form.text_field :city %>
730
730
  <% end %>
731
731
  </erb>
@@ -741,7 +741,7 @@ As a general rule the final input name is the concatenation of the name given to
741
741
  As a shortcut you can append [] to the name and omit the +:index+ option. This is the same as specifying +:index => address+ so
742
742
 
743
743
  <erb>
744
- <% fields_for 'person[address][primary][]', address do |address_form| %>
744
+ <%= fields_for 'person[address][primary][]', address do |address_form| %>
745
745
  <%= address_form.text_field :city %>
746
746
  <% end %>
747
747
  </erb>
@@ -752,6 +752,7 @@ h3. Building Complex Forms
752
752
 
753
753
  Many apps grow beyond simple forms editing a single object. For example when creating a Person you might want to allow the user to (on the same form) create multiple address records (home, work, etc.). When later editing that person the user should be able to add, remove or amend addresses as necessary. While this guide has shown you all the pieces necessary to handle this, Rails does not yet have a standard end-to-end way of accomplishing this, but many have come up with viable approaches. These include:
754
754
 
755
+ * As of Rails 2.3, Rails includes "Nested Attributes":./2_3_release_notes.html#nested-attributes and "Nested Object Forms":./2_3_release_notes.html#nested-object-forms
755
756
  * Ryan Bates' series of Railscasts on "complex forms":http://railscasts.com/episodes/75
756
757
  * Handle Multiple Models in One Form from "Advanced Rails Recipes":http://media.pragprog.com/titles/fr_arr/multiple_models_one_form.pdf
757
758
  * Eloy Duran's "complex-forms-examples":http://github.com/alloy/complex-form-examples/ application
@@ -20,7 +20,7 @@ h3. First contact
20
20
  When you create an application using the +rails+ command, you are in fact using a Rails generator. After that, you can get a list of all available generators by just invoking +rails generate+:
21
21
 
22
22
  <shell>
23
- $ rails myapp
23
+ $ rails new myapp
24
24
  $ cd myapp
25
25
  $ rails generate
26
26
  </shell>
@@ -88,9 +88,7 @@ And it will create a new generator as follow:
88
88
 
89
89
  <ruby>
90
90
  class InitializerGenerator < Rails::Generators::NamedBase
91
- def self.source_root
92
- @source_root ||= File.expand_path(File.join(File.dirname(__FILE__), 'templates'))
93
- end
91
+ source_root File.expand_path("../templates", __FILE__)
94
92
  end
95
93
  </ruby>
96
94
 
@@ -115,9 +113,7 @@ And now let's change the generator to copy this template when invoked:
115
113
 
116
114
  <ruby>
117
115
  class InitializerGenerator < Rails::Generators::NamedBase
118
- def self.source_root
119
- @source_root ||= File.expand_path(File.join(File.dirname(__FILE__), 'templates'))
120
- end
116
+ source_root File.expand_path("../templates", __FILE__)
121
117
 
122
118
  def copy_initializer_file
123
119
  copy_file "initializer.rb", "config/initializers/#{file_name}.rb"
@@ -135,21 +131,18 @@ We can see that now a initializer named foo was created at +config/initializers/
135
131
 
136
132
  h3. Generators lookup
137
133
 
138
- Now that we know how to create generators, we must know where Rails looks for generators before invoking them. When we invoke the initializer generator, Rails looks at the following paths in the given order:
134
+ With our first generator created, we must discuss briefly generators lookup. The way Rails finds generators is exactly the same way Ruby find files, i.e. using +$LOAD_PATHS+.
135
+
136
+ For instance, when you say +rails g initializer foo+, rails knows you want to invoke the initializer generator and then search for the following generators in the $LOAD_PATHS:
139
137
 
140
138
  <shell>
141
- RAILS_APP/lib/generators
142
- RAILS_APP/lib/rails_generators
143
- RAILS_APP/vendor/plugins/*/lib/generators
144
- RAILS_APP/vendor/plugins/*/lib/rails_generators
145
- GEMS_PATH/*/lib/generators
146
- GEMS_PATH/*/lib/rails_generators
147
- ~/rails/generators
148
- ~/rails/rails_generators
149
- RAILS_GEM/lib/rails/generators
139
+ rails/generators/initializer/initializer_generator.rb
140
+ generators/initializer/initializer_generator.rb
141
+ rails/generators/initializer_generator.rb
142
+ generators/initializer_generator.rb
150
143
  </shell>
151
144
 
152
- First Rails looks for generators in your application, then in plugins and/or gems, then in your home and finally the builtin generators. One very important thing to keep in mind is that in Rails 3.0 and after it only looks for generators in gems being used in your application. So if you have rspec installed as a gem, but it's not declared in your application, Rails won't be able to invoke it.
145
+ If none of them is found, it raises an error message.
153
146
 
154
147
  h3. Customizing your workflow
155
148
 
@@ -183,7 +176,6 @@ $ rails generate scaffold User name:string
183
176
  create app/views/users/show.html.erb
184
177
  create app/views/users/new.html.erb
185
178
  create app/views/users/_form.html.erb
186
- create app/views/layouts/users.html.erb
187
179
  invoke test_unit
188
180
  create test/functional/users_controller_test.rb
189
181
  invoke helper
@@ -284,7 +276,7 @@ end
284
276
  end
285
277
  </ruby>
286
278
 
287
- Now, when the helper generator is invoked and let's say test unit is configured as test framework, it will try to invoke both +MyHelper::Generators::TestUnitGenerator+ and +TestUnit::Generators::MyHelperGenerator+. Since none of those are defined, we can tell our generator to invoke +TestUnit::Generators::HelperGenerator+ instead, which is defined since it's a Rails hook. To do that, we just need to add:
279
+ Now, when the helper generator is invoked and let's say test unit is configured as test framework, it will try to invoke both +MyHelper::Generators::TestUnitGenerator+ and +TestUnit::Generators::MyHelperGenerator+. Since none of those are defined, we can tell our generator to invoke +TestUnit::Generators::HelperGenerator+ instead, which is defined since it's a Rails generator. To do that, we just need to add:
288
280
 
289
281
  <ruby>
290
282
  # Search for :helper instead of :my_helper
@@ -330,14 +322,10 @@ config.generators do |g|
330
322
  g.template_engine :erb
331
323
  g.test_framework :shoulda, :fixture => false
332
324
  g.stylesheets false
333
- end
334
- </ruby>
335
325
 
336
- And at the end of the same file:
337
-
338
- <ruby>
339
- require 'rails/generators'
340
- Rails::Generators.fallbacks[:shoulda] = :test_unit
326
+ # Add a fallback!
327
+ g.fallbacks[:should] = :test_unit
328
+ end
341
329
  </ruby>
342
330
 
343
331
  Now, if create a Comment scaffold, you will see that shoulda generators are being invoked, and at the end, they are just falling back to test unit generators:
@@ -369,10 +357,12 @@ $ rails generate scaffold Comment body:text
369
357
  create test/unit/helpers/comments_helper_test.rb
370
358
  </shell>
371
359
 
372
- Such tool allows your generators to have single responsibility, increasing the code reuse and reducing the amount of code duplication.
360
+ Such tool allows your generators to have single responsibility, increasing the code reuse and reducing the amount of duplication.
373
361
 
374
362
  h3. Changelog
375
363
 
376
364
  "Lighthouse Ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/102
377
365
 
378
- * November 20, 2009: First release version by José Valim
366
+ * April 30, 2010: Reviewed by José Valim
367
+
368
+ * November 20, 2009: First version by José Valim
@@ -16,6 +16,9 @@ h3. Guide Assumptions
16
16
  This guide is designed for beginners who want to get started with a Rails application from scratch. It does not assume that you have any prior experience with Rails. However, to get the most out of it, you need to have some prerequisites installed:
17
17
 
18
18
  * The "Ruby":http://www.ruby-lang.org/en/downloads language version 1.8.7 or higher
19
+
20
+ TIP: Note that Ruby 1.8.7 p248 and p249 has marshaling bugs that crash Rails 3.0.0. Ruby Enterprise Edition have these fixed since release 1.8.7-2010.02 though. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaults on Rails 3.0.0, so if you want to use Rails 3 with 1.9.x jump on 1.9.2 for smooth sailing.
21
+
19
22
  * The "RubyGems":http://rubyforge.org/frs/?group_id=126 packaging system
20
23
  * A working installation of the "SQLite3 Database":http://www.sqlite.org
21
24
 
@@ -87,11 +90,11 @@ Action View manages the views of your Rails application. It can create both HTML
87
90
 
88
91
  h5. Action Dispatch
89
92
 
90
- Action Dispatch handles routing of web requests and dispatches them as you want, either to your application, any other Rack application.
93
+ Action Dispatch handles routing of web requests and dispatches them as you want, either to your application or any other Rack application.
91
94
 
92
95
  h5. Action Mailer
93
96
 
94
- Action Mailer is a framework for building e-mail services. You can use Action Mailer to send emails based on flexible templates, or to receive and process incoming email.
97
+ Action Mailer is a framework for building e-mail services. You can use Action Mailer to receive and process incoming email and send simple plain text or complex multipart emails based on flexible templates.
95
98
 
96
99
  h5. Active Model
97
100
 
@@ -157,7 +160,7 @@ The best way to use this guide is to follow each step as it happens, no code or
157
160
  To begin, open a terminal, navigate to a folder where you have rights to create files, and type:
158
161
 
159
162
  <shell>
160
- $ rails blog
163
+ $ rails new blog
161
164
  </shell>
162
165
 
163
166
  This will create a Rails application called Blog in a directory called blog.
@@ -232,13 +235,13 @@ If you choose to use MySQL instead of the shipped Sqlite3 database, your +config
232
235
 
233
236
  <yaml>
234
237
  development:
235
- adapter: mysql
236
- encoding: utf8
237
- database: blog_development
238
- pool: 5
239
- username: root
240
- password:
241
- socket: /tmp/mysql.sock
238
+ adapter: mysql
239
+ encoding: utf8
240
+ database: blog_development
241
+ pool: 5
242
+ username: root
243
+ password:
244
+ socket: /tmp/mysql.sock
242
245
  </yaml>
243
246
 
244
247
  If your development computer's MySQL installation includes a root user with an empty password, this configuration should work for you. Otherwise, change the username and password in the +development+ section as appropriate.
@@ -249,12 +252,12 @@ Finally if you choose to use PostgreSQL, your +config/database.yml+ will be cust
249
252
 
250
253
  <yaml>
251
254
  development:
252
- adapter: postgresql
253
- encoding: unicode
254
- database: blog_development
255
- pool: 5
256
- username: blog
257
- password:
255
+ adapter: postgresql
256
+ encoding: unicode
257
+ database: blog_development
258
+ pool: 5
259
+ username: blog
260
+ password:
258
261
  </yaml>
259
262
 
260
263
  Change the username and password in the +development+ section as appropriate.
@@ -356,19 +359,18 @@ The scaffold generator will build 15 files in your application, along with some
356
359
  |_.File |_.Purpose|
357
360
  |db/migrate/20100207214725_create_posts.rb.rb |Migration to create the posts table in your database (your name will include a different timestamp)|
358
361
  |app/models/post.rb |The Post model|
359
- |test/unit/post_test.rb |Unit testing harness for the posts model|
360
362
  |test/fixtures/posts.yml |Dummy posts for use in testing|
361
363
  |app/controllers/posts_controller.rb |The Posts controller|
362
364
  |app/views/posts/index.html.erb |A view to display an index of all posts |
363
365
  |app/views/posts/edit.html.erb |A view to edit an existing post|
364
366
  |app/views/posts/show.html.erb |A view to display a single post|
365
367
  |app/views/posts/new.html.erb |A view to create a new post|
366
- |app/views/posts/_form.html.erb |A view to control the overall look and feel of the other posts views|
367
- |app/views/layouts/posts.html.erb |A view to control the overall look and feel of the other posts views|
368
+ |app/views/posts/_form.html.erb |A partial to control the overall look and feel of the form used in edit and new views|
369
+ |app/helpers/posts_helper.rb |Helper functions to be used from the post views|
370
+ |test/unit/post_test.rb |Unit testing harness for the posts model|
368
371
  |test/functional/posts_controller_test.rb |Functional testing harness for the posts controller|
369
- |app/helpers/posts_helper.rb |Helper functions to be used from the posts views|
370
- |config/routes.rb |Edited to include routing information for posts|
371
372
  |test/unit/helpers/posts_helper_test.rb |Unit testing harness for the posts helper|
373
+ |config/routes.rb |Edited to include routing information for posts|
372
374
  |public/stylesheets/scaffold.css |Cascading style sheet to make the scaffolded views look better|
373
375
 
374
376
  h4. Running a Migration
@@ -395,7 +397,7 @@ class CreatePosts < ActiveRecord::Migration
395
397
  end
396
398
  </ruby>
397
399
 
398
- The above migration creates two methods, +up+, called when you run this migration into the database, and +down+ in case you need to reverse the changes made by this migration at a later date. The +up+ command in this case creates a +posts+ table with two string columns and a text column. It also is creating two timestamp fields to track record creation and updating. More information about Rails migrations can be found in the "Rails Database Migrations":migrations.html guide.
400
+ The above migration creates two methods, +up+, called when you run this migration into the database, and +down+ in case you need to reverse the changes made by this migration at a later date. The +up+ command in this case creates a +posts+ table with two string columns and a text column. It also creates two timestamp fields to track record creation and updating. More information about Rails migrations can be found in the "Rails Database Migrations":migrations.html guide.
399
401
 
400
402
  At this point, you can use a rake command to run the migration:
401
403
 
@@ -504,7 +506,7 @@ def index
504
506
  end
505
507
  </ruby>
506
508
 
507
- This code sets the +@posts+ instance variable to an array of all posts in the database. +Post.all+ calls the +Post+ model to return all of the posts that are currently in the database, with no limiting conditions.
509
+ +Post.all+ calls the +Post+ model to return all of the posts currently in the database. The result of this call is an array containing the posts which has been saved in an instance variable called +@posts+.
508
510
 
509
511
  TIP: For more information on finding records with Active Record, see "Active Record Query Interface":active_record_querying.html.
510
512
 
@@ -543,7 +545,7 @@ The +respond_to+ block handles both HTML and XML calls to this action. If you br
543
545
  This view iterates over the contents of the +@posts+ array to display content and links. A few things to note in the view:
544
546
 
545
547
  * +link_to+ builds a hyperlink to a particular destination
546
- * +edit_post_path+ is a helper that Rails provides as part of RESTful routing. You'll see a variety of these helpers for the different actions that the controller includes.
548
+ * +edit_post_path+ and +new_post_path+ are helpers that Rails provides as part of RESTful routing. You'll see a variety of these helpers for the different actions that the controller includes.
547
549
 
548
550
  NOTE. In previous versions of Rails, you had to use +&lt;%=h post.name %&gt;+ so that any HTML would be escaped before being inserted into the page. In Rails 3.0, this is now the default. To get unescaped HTML, you now use +&lt;%= raw post.name %&gt;+.
549
551
 
@@ -551,19 +553,19 @@ TIP: For more details on the rendering process, see "Layouts and Rendering in Ra
551
553
 
552
554
  h4. Customizing the Layout
553
555
 
554
- The view is only part of the story of how HTML is displayed in your web browser. Rails also has the concept of +layouts+, which are containers for views. When Rails renders a view to the browser, it does so by putting the view's HTML into a layout's HTML. The +rails generate scaffold+ command automatically created a default layout, +app/views/layouts/posts.html.erb+, for the posts. Open this layout in your editor and modify the +body+ tag:
556
+ The view is only part of the story of how HTML is displayed in your web browser. Rails also has the concept of +layouts+, which are containers for views. When Rails renders a view to the browser, it does so by putting the view's HTML into a layout's HTML. In previous versions of Rails, the +rails generate scaffold+ command would automatically create a controller specific layout, like +app/views/layouts/posts.html.erb+, for the posts controller. However this has been changed in Rails 3.0. A application specific +layout+ is used for all the controllers and can be found in +app/views/layouts/application.html.erb+. Open this layout in your editor and modify the +body+ tag:
555
557
 
556
558
  <erb>
557
559
  <!DOCTYPE html>
558
560
  <html>
559
561
  <head>
560
- <title>Posts: <%= controller.action_name %></title>
561
- <%= stylesheet_link_tag 'scaffold' %>
562
+ <title>Blog</title>
563
+ <%= stylesheet_link_tag :all %>
564
+ <%= javascript_include_tag :defaults %>
565
+ <%= csrf_meta_tag %>
562
566
  </head>
563
567
  <body style="background: #EEEEEE;">
564
568
 
565
- <p class="notice"><%= notice %></p>
566
-
567
569
  <%= yield %>
568
570
 
569
571
  </body>
@@ -603,7 +605,16 @@ If you take a look at +views/posts/_form.html.erb+ file, you will see the follow
603
605
 
604
606
  <erb>
605
607
  <%= form_for(@post) do |f| %>
606
- <%= f.error_messages %>
608
+ <% if @post.errors.any? %>
609
+ <div id="errorExplanation">
610
+ <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
611
+ <ul>
612
+ <% @post.errors.full_messages.each do |msg| %>
613
+ <li><%= msg %></li>
614
+ <% end %>
615
+ </ul>
616
+ </div>
617
+ <% end %>
607
618
 
608
619
  <div class="field">
609
620
  <%= f.label :name %><br />
@@ -654,7 +665,7 @@ def create
654
665
  end
655
666
  </ruby>
656
667
 
657
- The +create+ action instantiates a new Post object from the data supplied by the user on the form, which Rails makes available in the +params+ hash. After successfully saving the new post, returns the appropriate format that the user has requested (HTML in our case). It then redirects the user to the resulting post +show+ action and sets a notice to the user that the Post was successfully created.
668
+ The +create+ action instantiates a new Post object from the data supplied by the user on the form, which Rails makes available in the +params+ hash. After successfully saving the new post, +create+ returns the appropriate format that the user has requested (HTML in our case). It then redirects the user to the resulting post +show+ action and sets a notice to the user that the Post was successfully created.
658
669
 
659
670
  If the post was not successfully saved, due to a validation error, then the controller returns the user back to the +new+ action with any error messages so that the user has the chance to fix the error and try again.
660
671
 
@@ -678,6 +689,8 @@ end
678
689
  The +show+ action uses +Post.find+ to search for a single record in the database by its id value. After finding the record, Rails displays it by using +show.html.erb+:
679
690
 
680
691
  <erb>
692
+ <p class="notice"><%= notice %></p>
693
+
681
694
  <p>
682
695
  <b>Name:</b>
683
696
  <%= @post.name %>
@@ -742,7 +755,7 @@ def update
742
755
  end
743
756
  </ruby>
744
757
 
745
- In the +update+ action, Rails first uses the +:id+ parameter passed back from the edit view to locate the database record that's being edited. The +update_attributes+ call then takes the rest of the parameters from the request and applies them to this record. If all goes well, the user is redirected to the post's +show+ view. If there are any problems, it's back to +edit+ to correct them.
758
+ In the +update+ action, Rails first uses the +:id+ parameter passed back from the edit view to locate the database record that's being edited. The +update_attributes+ call then takes the rest of the parameters from the request and applies them to this record. If all goes well, the user is redirected to the post's +show+ view. If there are any problems, it's back to the +edit+ view to correct them.
746
759
 
747
760
  h4. Destroying a Post
748
761
 
@@ -764,7 +777,7 @@ The +destroy+ method of an Active Record model instance removes the correspondin
764
777
 
765
778
  h3. Adding a Second Model
766
779
 
767
- Now that you've seen what's in a model built with scaffolding, it's time to add a second model to the application. The second model will handle comments on blog posts.
780
+ Now that you've seen how a model built with scaffolding looks like, it's time to add a second model to the application. The second model will handle comments on blog posts.
768
781
 
769
782
  h4. Generating a Model
770
783
 
@@ -878,18 +891,21 @@ With the model in hand, you can turn your attention to creating a matching contr
878
891
  $ rails generate controller Comments
879
892
  </shell>
880
893
 
881
- This creates four files:
894
+ This creates four files and one empty directory:
882
895
 
883
896
  * +app/controllers/comments_controller.rb+ - The controller
884
897
  * +app/helpers/comments_helper.rb+ - A view helper file
885
898
  * +test/functional/comments_controller_test.rb+ - The functional tests for the controller
886
899
  * +test/unit/helpers/comments_helper_test.rb+ - The unit tests for the helper
900
+ * +app/views/comments/+ - Views of the controller are stored here
887
901
 
888
902
  Like with any blog, our readers will create their comments directly after reading the post, and once they have added their comment, will be sent back to the post show page to see their comment now listed. Due to this, our +CommentsController+ is there to provide a method to create comments and delete SPAM comments when they arrive.
889
903
 
890
904
  So first, we'll wire up the Post show template (+/app/views/posts/show.html.erb+) to let us make a new comment:
891
905
 
892
906
  <erb>
907
+ <p class="notice"><%= notice %></p>
908
+
893
909
  <p>
894
910
  <b>Name:</b>
895
911
  <%= @post.name %>
@@ -940,11 +956,13 @@ end
940
956
 
941
957
  You'll see a bit more complexity here than you did in the controller for posts. That's a side-effect of the nesting that you've set up; each request for a comment has to keep track of the post to which the comment is attached, thus the initial find action to the Post model to get the post in question.
942
958
 
943
- In addition, the code takes advantage of some of the methods available for an association. For example, in the +new+ method, it calls
959
+ In addition, the code takes advantage of some of the methods available for an association. We use the +create+ method on +@post.comments+ to create and save the comment. This will automatically link the comment so that it belongs to that particular post.
944
960
 
945
- Once we have made the new comment, we send the user back to the +post_path(@post)+ URL. This runs the +show+ action of the +PostsController+ which then renders the +show.html.erb+ template where we want the comment to show, so then, we'll add that to the +app/view/posts/show.html.erb+.
961
+ Once we have made the new comment, we send the user back to the original post using the +post_path(@post)+ helper. As we have already seen, this calls the +show+ action of the +PostsController+ which in turn renders the +show.html.erb+ template. This is where we want the comment to show, so let's add that to the +app/view/posts/show.html.erb+.
946
962
 
947
963
  <erb>
964
+ <p class="notice"><%= notice %></p>
965
+
948
966
  <p>
949
967
  <b>Name:</b>
950
968
  <%= @post.name %>
@@ -1000,11 +1018,11 @@ Now you can add posts and comments to your blog and have them show up in the rig
1000
1018
 
1001
1019
  h3. Refactorization
1002
1020
 
1003
- Now that we have Posts and Comments working, we can take a look at the +app/views/posts/show.html.erb+ template, it is getting long and awkward, we can use partials to clean this up.
1021
+ Now that we have Posts and Comments working, if we take a look at the +app/views/posts/show.html.erb+ template, it's getting long and awkward. We can use partials to clean this up.
1004
1022
 
1005
1023
  h4. Rendering Partial Collections
1006
1024
 
1007
- First will make a comment partial to extract showing all the comments for the post, so make a file +app/views/comments/_comment.html.erb+ and put into it:
1025
+ First we will make a comment partial to extract showing all the comments for the post. Create the file +app/views/comments/_comment.html.erb+ and put the following into it:
1008
1026
 
1009
1027
  <erb>
1010
1028
  <p>
@@ -1021,6 +1039,8 @@ First will make a comment partial to extract showing all the comments for the po
1021
1039
  Then in the +app/views/posts/show.html.erb+ you can change it to look like the following:
1022
1040
 
1023
1041
  <erb>
1042
+ <p class="notice"><%= notice %></p>
1043
+
1024
1044
  <p>
1025
1045
  <b>Name:</b>
1026
1046
  <%= @post.name %>
@@ -1090,6 +1110,8 @@ Lets also move that new comment section out to it's own partial, again, you crea
1090
1110
  Then you make the +app/views/posts/show.html.erb+ look like the following:
1091
1111
 
1092
1112
  <erb>
1113
+ <p class="notice"><%= notice %></p>
1114
+
1093
1115
  <p>
1094
1116
  <b>Name:</b>
1095
1117
  <%= @post.name %>
@@ -1120,7 +1142,7 @@ Then you make the +app/views/posts/show.html.erb+ look like the following:
1120
1142
 
1121
1143
  The second render just defines the partial template we want to render, <tt>comments/form</tt>, Rails is smart enough to spot the forward slash in that string and realise that you want to render the <tt>_form.html.erb</tt> file in the <tt>app/views/comments</tt> directory.
1122
1144
 
1123
- The +@post+ object is available any partials rendered in the view because we defined it as an instance variable.
1145
+ The +@post+ object is available to any partials rendered in the view because we defined it as an instance variable.
1124
1146
 
1125
1147
  h3. Deleting Comments
1126
1148
 
@@ -1172,7 +1194,7 @@ The +destroy+ action will find the post we are looking at, locate the comment wi
1172
1194
 
1173
1195
  h4. Deleting Associated Objects
1174
1196
 
1175
- If you decide at some point to delete a post, you likely want to delete the comments associated with that post as well. You can do so by taking advantage of the association option +dependent+. All you need to do is modify the +post.rb+ as follows:
1197
+ If you delete a post then it's associated comments will also need to be deleted. Otherwise they would simply occupy space in the database. Rails allows you to use the +dependent+ option of an association to achieve this. Modify the Post model, +app/models/post.rb+, as follows:
1176
1198
 
1177
1199
  <ruby>
1178
1200
  class Post < ActiveRecord::Base
@@ -1185,9 +1207,9 @@ end
1185
1207
 
1186
1208
  h3. Security
1187
1209
 
1188
- Before you publish your blog online, you will most likely want to prevent just anyone from being able to add, edit and delete posts or delete comments.
1210
+ If you were to publish your blog online, anybody would be able to add, edit and delete posts or delete comments.
1189
1211
 
1190
- Rails provides a very simple http authentication system that will work nicely in this situation. First, we enable simple HTTP based authentication in our <tt>app/controllers/application_controller.rb</tt>:
1212
+ Rails provides a very simple HTTP authentication system that will work nicely in this situation. First, we enable simple HTTP based authentication in our <tt>app/controllers/application_controller.rb</tt>:
1191
1213
 
1192
1214
  <ruby>
1193
1215
  class ApplicationController < ActionController::Base
@@ -1242,7 +1264,7 @@ Now if you try to create a new post, you will be greeted with a basic HTTP Authe
1242
1264
 
1243
1265
  h3. Building a Multi-Model Form
1244
1266
 
1245
- Another piece of your average blog is the ability to tag posts. This requires that your application edits more than one thing on a single form. Rails offers support for nested forms.
1267
+ Another feature of your average blog is the ability to tag posts. To implement this feature your application needs to interact with more than one model on a single form. Rails offers support for nested forms.
1246
1268
 
1247
1269
  To demonstrate this, we will add support for giving each post multiple tags, right in the form where you create the post. First, create a new model to hold the tags:
1248
1270
 
@@ -1279,7 +1301,16 @@ We will modify +views/posts/_form.html.erb+ to render a partial to make a tag:
1279
1301
  <erb>
1280
1302
  <% @post.tags.build %>
1281
1303
  <%= form_for(@post) do |post_form| %>
1282
- <%= post_form.error_messages %>
1304
+ <% if @post.errors.any? %>
1305
+ <div id="errorExplanation">
1306
+ <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
1307
+ <ul>
1308
+ <% @post.errors.full_messages.each do |msg| %>
1309
+ <li><%= msg %></li>
1310
+ <% end %>
1311
+ </ul>
1312
+ </div>
1313
+ <% end %>
1283
1314
 
1284
1315
  <div class="field">
1285
1316
  <%= post_form.label :name %><br />
@@ -1302,16 +1333,16 @@ We will modify +views/posts/_form.html.erb+ to render a partial to make a tag:
1302
1333
  <% end %>
1303
1334
  </erb>
1304
1335
 
1305
- This example shows another option of the render helper, being able to pass in local variables, in this case, we want the local variable +form+ in the partial to refer to the +post_form+ object.
1336
+ Note that we have changed the +f+ in +form_for(@post) do |f|+ to +post_form+ to make it easier to understand what is going on.
1306
1337
 
1307
- You will also note that we also have changed the +f+ in <tt>form_for(@post) do |f|</tt> to <tt>post_form</tt> to clarify what is going on somewhat.
1338
+ This example shows another option of the render helper, being able to pass in local variables, in this case, we want the local variable +form+ in the partial to refer to the +post_form+ object.
1308
1339
 
1309
1340
  We also add a <tt>@post.tags.build</tt> at the top of this form, this is to make sure there is a new tag ready to have it's name filled in by the user. If you do not build the new tag, then the form will not appear as there is no new Tag object ready to create.
1310
1341
 
1311
1342
  Now create the folder <tt>app/views/tags</tt> and make a file in there called <tt>_form.html.erb</tt> which contains the form for the tag:
1312
1343
 
1313
1344
  <erb>
1314
- <% form.fields_for :tags do |tag_form| %>
1345
+ <%= form.fields_for :tags do |tag_form| %>
1315
1346
  <div class="field">
1316
1347
  <%= tag_form.label :name, 'Tag:' %>
1317
1348
  <%= tag_form.text_field :name %>
@@ -1328,6 +1359,8 @@ Now create the folder <tt>app/views/tags</tt> and make a file in there called <t
1328
1359
  Finally, we will edit the <tt>app/views/posts/show.html.erb</tt> template to show our tags.
1329
1360
 
1330
1361
  <erb>
1362
+ <p class="notice"><%= notice %></p>
1363
+
1331
1364
  <p>
1332
1365
  <b>Name:</b>
1333
1366
  <%= @post.name %>
@@ -1381,6 +1414,8 @@ end
1381
1414
  Now you can edit the view in <tt>app/views/posts/show.html.erb</tt> to look like this:
1382
1415
 
1383
1416
  <erb>
1417
+ <p class="notice"><%= notice %></p>
1418
+
1384
1419
  <p>
1385
1420
  <b>Name:</b>
1386
1421
  <%= @post.name %>
@@ -1427,14 +1462,36 @@ Rails also comes with built-in help that you can generate using the rake command
1427
1462
  * Running +rake doc:guides+ will put a full copy of the Rails Guides in the +doc/guides+ folder of your application. Open +doc/guides/index.html+ in your web browser to explore the Guides.
1428
1463
  * Running +rake doc:rails+ will put a full copy of the API documentation for Rails in the +doc/api+ folder of your application. Open +doc/api/index.html+ in your web browser to explore the API documentation.
1429
1464
 
1465
+ h3. Configuration Gotchas
1466
+
1467
+ The easiest way to work with Rails is to store all external data as UTF-8. If you don't, Ruby libraries and Rails will often be able to convert your native data into UTF-8, but this doesn't always work reliably, so you're better off ensuring that all external data is UTF-8.
1468
+
1469
+ If you have made a mistake in this area, the most common symptom is a black diamond with a question mark inside appearing in the browser. Another common symptom is characters like "ü" appearing instead of "ü". Rails takes a number of internal steps to mitigate common causes of these problems that can be automatically detected and corrected. However, if you have external data that is not stored as UTF-8, it can occasionally result in these kinds of issues that cannot be automatically detected by Rails and corrected.
1470
+
1471
+ Two very common sources of data that are not UTF-8:
1472
+ * Your text editor: Most text editors (such as Textmate), default to saving files as
1473
+ UTF-8. If your text editor does not, this can result in special characters that you
1474
+ enter in your templates (such as é) to appear as a diamond with a question mark inside
1475
+ in the browser. This also applies to your I18N translation files.
1476
+ Most editors that do not already default to UTF-8 (such as some versions of
1477
+ Dreamweaver) offer a way to change the default to UTF-8. Do so.
1478
+ * Your database. Rails defaults to converting data from your database into UTF-8 at
1479
+ the boundary. However, if your database is not using UTF-8 internally, it may not
1480
+ be able to store all characters that your users enter. For instance, if your database
1481
+ is using Latin-1 internally, and your user enters a Russian, Hebrew, or Japanese
1482
+ character, the data will be lost forever once it enters the database. If possible,
1483
+ use UTF-8 as the internal storage of your database.
1430
1484
 
1431
1485
  h3. Changelog
1432
1486
 
1433
1487
  "Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/2
1434
1488
 
1489
+ * May 16, 2010: Added a section on configuration gotchas to address common encoding problems that people might have by "Yehuda Katz":http://www.yehudakatz.com
1490
+ * April 30, 2010: Fixes, editing and updating of code samples by "Rohit Arondekar":http://rohitarondekar.com
1491
+ * April 25, 2010: Couple of more minor fixups "Mikel Lindsaar":credits.html#raasdnil
1435
1492
  * April 1, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
1436
- * February 8, 2010: Full re-write for Rails 3.0-beta, added helpers and before_filters, refactored code by "Mikel Lindsaar":credits:html#raasdnil
1437
- * January 24, 2010: Re-write for Rails 3.0 by "Mikel Lindsaar":credits:html#raasdnil
1493
+ * February 8, 2010: Full re-write for Rails 3.0-beta, added helpers and before_filters, refactored code by "Mikel Lindsaar":credits.html#raasdnil
1494
+ * January 24, 2010: Re-write for Rails 3.0 by "Mikel Lindsaar":credits.html#raasdnil
1438
1495
  * July 18, 2009: Minor cleanup in anticipation of Rails 2.3.3 by "Mike Gunderloy":credits.html#mgunderloy
1439
1496
  * February 1, 2009: Updated for Rails 2.3 by "Mike Gunderloy":credits.html#mgunderloy
1440
1497
  * November 3, 2008: Formatting patch from Dave Rothlisberger