aboutsummaryrefslogtreecommitdiffstats
path: root/railties/doc/guides
diff options
context:
space:
mode:
Diffstat (limited to 'railties/doc/guides')
-rw-r--r--railties/doc/guides/actioncontroller/actioncontroller.txt4
-rw-r--r--railties/doc/guides/actioncontroller/cookies.txt30
-rw-r--r--railties/doc/guides/actioncontroller/filters.txt23
-rw-r--r--railties/doc/guides/actioncontroller/http_auth.txt2
-rw-r--r--railties/doc/guides/actioncontroller/introduction.txt2
-rw-r--r--railties/doc/guides/actioncontroller/methods.txt2
-rw-r--r--railties/doc/guides/actioncontroller/parameter_filtering.txt2
-rw-r--r--railties/doc/guides/actioncontroller/params.txt4
-rw-r--r--railties/doc/guides/actioncontroller/request_response_objects.txt4
-rw-r--r--railties/doc/guides/actioncontroller/rescue.txt66
-rw-r--r--railties/doc/guides/actioncontroller/session.txt93
-rw-r--r--railties/doc/guides/actioncontroller/streaming.txt10
-rw-r--r--railties/doc/guides/actioncontroller/verification.txt39
-rw-r--r--railties/doc/guides/actionview/layouts_and_rendering.txt19
-rw-r--r--railties/doc/guides/activerecord/association_basics.txt34
-rw-r--r--railties/doc/guides/activerecord/finders.txt137
-rw-r--r--railties/doc/guides/getting_started_with_rails/getting_started_with_rails.txt1150
-rw-r--r--railties/doc/guides/index.txt2
-rw-r--r--railties/doc/guides/routing/routing_outside_in.txt26
-rw-r--r--railties/doc/guides/securing_rails_applications/security.txt8
-rw-r--r--railties/doc/guides/testing_rails_applications/testing_rails_applications.txt918
21 files changed, 1797 insertions, 778 deletions
diff --git a/railties/doc/guides/actioncontroller/actioncontroller.txt b/railties/doc/guides/actioncontroller/actioncontroller.txt
index c5a594d713..0b884e590b 100644
--- a/railties/doc/guides/actioncontroller/actioncontroller.txt
+++ b/railties/doc/guides/actioncontroller/actioncontroller.txt
@@ -15,6 +15,8 @@ include::cookies.txt[]
include::filters.txt[]
+include::verification.txt[]
+
include::request_response_objects.txt[]
include::http_auth.txt[]
@@ -23,6 +25,4 @@ include::streaming.txt[]
include::parameter_filtering.txt[]
-include::verification.txt[]
-
include::rescue.txt[]
diff --git a/railties/doc/guides/actioncontroller/cookies.txt b/railties/doc/guides/actioncontroller/cookies.txt
index a845e452b2..d451f3f7a6 100644
--- a/railties/doc/guides/actioncontroller/cookies.txt
+++ b/railties/doc/guides/actioncontroller/cookies.txt
@@ -2,22 +2,30 @@
Your application can store small amounts of data on the client - called cookies - that will be persisted across requests and even sessions. Rails provides easy access to cookies via the `cookies` method, which - much like the `session` - works like a hash:
-TODO: Find a real-world example where cookies are used
-
[source, ruby]
-----------------------------------------
-class FooController < ApplicationController
-
- def foo
- cookies[:foo] = "bar"
- end
+class CommentsController < ApplicationController
- def display_foo
- @foo = cookies[:foo]
+ def new
+ #Auto-fill the commenter's name if it has been stored in a cookie
+ @comment = Comment.new(:name => cookies[:commenter_name])
end
- def remove_foo
- cookies.delete(:foo)
+ def create
+ @comment = Comment.new(params[:comment])
+ if @comment.save
+ flash[:notice] = "Thanks for your comment!"
+ if params[:remember_name]
+ # Remember the commenter's name
+ cookies[:commenter_name] = @comment.name
+ else
+ # Don't remember, and delete the name if it has been remembered before
+ cookies.delete(:commenter_name)
+ end
+ redirect_to @comment.article
+ else
+ render :action => "new"
+ end
end
end
diff --git a/railties/doc/guides/actioncontroller/filters.txt b/railties/doc/guides/actioncontroller/filters.txt
index 2baf92d6ef..a7b8d9727f 100644
--- a/railties/doc/guides/actioncontroller/filters.txt
+++ b/railties/doc/guides/actioncontroller/filters.txt
@@ -27,7 +27,7 @@ private
end
---------------------------------
-The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a before filter (a filter which is run before the action) renders or redirects, the action will not run. If there are additional filters scheduled to run after the rendering/redirecting filter, they are also cancelled. To use this filter in a controller, use the "before_filter":http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000704 method:
+The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a before filter (a filter which is run before the action) renders or redirects, the action will not run. If there are additional filters scheduled to run after the rendering/redirecting filter, they are also cancelled. To use this filter in a controller, use the link:http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000704[before_filter] method:
[source, ruby]
---------------------------------
@@ -38,7 +38,7 @@ class ApplicationController < ActionController::Base
end
---------------------------------
-In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this, so to prevent this filter from running you can use "skip_before_filter":http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000711 :
+In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this, so to prevent this filter from running you can use link:http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000711[skip_before_filter] :
[source, ruby]
---------------------------------
@@ -59,24 +59,27 @@ TODO: Find a real example for an around filter
[source, ruby]
---------------------------------
+# Example taken from the Rails API filter documentation:
+# http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html
class ApplicationController < Application
- around_filter :foo
+ around_filter :catch_exceptions
private
- def foo
- logger.debug("Action has not been run yet")
- yield #Run the action
- logger.debug("Action has been run")
+ def catch_exceptions
+ yield
+ rescue => exception
+ logger.debug "Caught exception! #{exception}"
+ raise
end
end
---------------------------------
-=== Other types of filters ===
+=== Other ways to use filters ===
-While the most common way to use filters is by creating private methods and using *_filter to add them, there are two other ways.
+While the most common way to use filters is by creating private methods and using *_filter to add them, there are two other ways to do the same thing.
The first is to use a block directly with the *_filter methods. The block receives the controller as an argument, and the `require_login` filter from above could be rewritte to use a block:
@@ -115,4 +118,4 @@ end
Again, this is not an ideal example for this filter, because it's not run in the scope of the controller but gets it passed as an argument. The filter class has a class method `filter` which gets run before or after the action, depending on if it's a before or after filter. Classes used as around filters can also use the same `filter` method, which will get run in the same way. The method must `yield` to execute the action. Alternatively, it can have both a `before` and an `after` method that are run before and after the action.
-The Rails API documentation has "more information and detail on using filters":http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html
+The Rails API documentation has link:http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html[more information on using filters].
diff --git a/railties/doc/guides/actioncontroller/http_auth.txt b/railties/doc/guides/actioncontroller/http_auth.txt
index 5a95de0bb3..7df0e635bf 100644
--- a/railties/doc/guides/actioncontroller/http_auth.txt
+++ b/railties/doc/guides/actioncontroller/http_auth.txt
@@ -1,6 +1,6 @@
== HTTP Basic Authentication ==
-Rails comes with built-in HTTP Basic authentication. This is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, we will create an administration section which will only be available by entering a username and a password into the browser's HTTP Basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, "authenticate_or_request_with_http_basic":http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Basic/ControllerMethods.html#M000610
+Rails comes with built-in HTTP Basic authentication. This is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, we will create an administration section which will only be available by entering a username and a password into the browser's HTTP Basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, link:http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Basic/ControllerMethods.html#M000610[authenticate_or_request_with_http_basic].
[source, ruby]
-------------------------------------
diff --git a/railties/doc/guides/actioncontroller/introduction.txt b/railties/doc/guides/actioncontroller/introduction.txt
index 35540bbc09..e4b0953b95 100644
--- a/railties/doc/guides/actioncontroller/introduction.txt
+++ b/railties/doc/guides/actioncontroller/introduction.txt
@@ -2,6 +2,6 @@
Action Controller is the C in MVC. After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output. Luckily, Action Controller does most of the groundwork for you and uses smart conventions to make this as straight-forward as possible.
-For most conventional RESTful applications, the controller will receive the request (this is invisible to the developer), fetch or save data from a model and use a view to create HTML output. If your controller needs to do things a little differently, that's not a problem, this is just the most common way for a controller to work.
+For most conventional RESTful applications, the controller will receive the request (this is invisible to you as the developer), fetch or save data from a model and use a view to create HTML output. If your controller needs to do things a little differently, that's not a problem, this is just the most common way for a controller to work.
A controller can thus be thought of as a middle man between models and views. It makes the model data available to the view so it can display it to the user, and it saves or updates data from the user to the model.
diff --git a/railties/doc/guides/actioncontroller/methods.txt b/railties/doc/guides/actioncontroller/methods.txt
index 0818dbb849..a1ef204adb 100644
--- a/railties/doc/guides/actioncontroller/methods.txt
+++ b/railties/doc/guides/actioncontroller/methods.txt
@@ -1,6 +1,6 @@
== Methods and actions ==
-A controller is a Ruby class which inherits from ActionController::Base and has methods just like any other class. Usually these methods correspond to actions in MVC, but they can just as well be helpful methods which can be called by actions. When your application receives a request, the routing will determine which controller and action to run. Then an instance of that controller will be created and the method corresponding to the action (the method with the same name as the action) is run.
+A controller is a Ruby class which inherits from ActionController::Base and has methods just like any other class. Usually these methods correspond to actions in MVC, but they can just as well be helpful methods which can be called by actions. When your application receives a request, the routing will determine which controller and action to run. Then an instance of that controller will be created and the method corresponding to the action (the method with the same name as the action) gets run.
[source, ruby]
----------------------------------------------
diff --git a/railties/doc/guides/actioncontroller/parameter_filtering.txt b/railties/doc/guides/actioncontroller/parameter_filtering.txt
index dce4b252c3..c4577d4f6d 100644
--- a/railties/doc/guides/actioncontroller/parameter_filtering.txt
+++ b/railties/doc/guides/actioncontroller/parameter_filtering.txt
@@ -1,6 +1,6 @@
== Parameter filtering ==
-Rails keeps a log file for each environment (development, test and production) in the "log" folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The "filter_parameter_logging":http://api.rubyonrails.org/classes/ActionController/Base.html#M000837 can be used to filter out sensitive information from the log. It works by replacing certain keys in the `params` hash with "[FILTERED]" before they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":
+Rails keeps a log file for each environment (development, test and production) in the "log" folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The link:http://api.rubyonrails.org/classes/ActionController/Base.html#M000837[filter_parameter_logging] method can be used to filter out sensitive information from the log. It works by replacing certain keys in the `params` hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":
[source, ruby]
-------------------------
diff --git a/railties/doc/guides/actioncontroller/params.txt b/railties/doc/guides/actioncontroller/params.txt
index 67f97b6135..7f494d7c9b 100644
--- a/railties/doc/guides/actioncontroller/params.txt
+++ b/railties/doc/guides/actioncontroller/params.txt
@@ -8,7 +8,7 @@ class ClientsController < ActionController::Base
# This action uses query string parameters because it gets run by a HTTP GET request,
# but this does not make any difference to the way in which the parameters are accessed.
- # The URL for this action would look like this in order to list activated clients: /clients/?status=activated
+ # The URL for this action would look like this in order to list activated clients: /clients?status=activated
def index
if params[:status] = "activated"
@clients = Client.activated
@@ -47,7 +47,7 @@ The value of `params[:ids]` will now be `["1", "2", "3"]`. Note that parameter v
To send a hash you include the key name inside the brackets:
-------------------------------------
-<form action="/clients">
+<form action="/clients" method="post">
<input type="text" name="client[name]" value="Acme" />
<input type="text" name="client[phone]" value="12345" />
<input type="text" name="client[address][postcode]" value="12345" />
diff --git a/railties/doc/guides/actioncontroller/request_response_objects.txt b/railties/doc/guides/actioncontroller/request_response_objects.txt
index d335523a25..493bd4cb43 100644
--- a/railties/doc/guides/actioncontroller/request_response_objects.txt
+++ b/railties/doc/guides/actioncontroller/request_response_objects.txt
@@ -1,10 +1,10 @@
== The request and response objects ==
-In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The `request` method contains an instance of "AbstractRequest":http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html and the `response` method contains the "response object":http://github.com/rails/rails/tree/master/actionpack/lib/action_controller/response.rb representing what is going to be sent back to the client.
+In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The `request` method contains an instance of link:http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html[AbstractRequest] and the `response` method contains the link:http://github.com/rails/rails/tree/master/actionpack/lib/action_controller/response.rb[response object] representing what is going to be sent back to the client.
=== The request ===
-The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the "Rails API documentation":http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html
+The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the link:http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html[API documentation].
* host - The hostname used for this request.
* domain - The hostname without the first part (usually "www").
diff --git a/railties/doc/guides/actioncontroller/rescue.txt b/railties/doc/guides/actioncontroller/rescue.txt
index 6ff7ea67d8..ec03006764 100644
--- a/railties/doc/guides/actioncontroller/rescue.txt
+++ b/railties/doc/guides/actioncontroller/rescue.txt
@@ -1,3 +1,67 @@
== Rescue ==
-Describe how to use rescue_from et al to rescue exceptions in controllers.
+Most likely your application is going to contain bugs or otherwise throw an exception that needs to be handled. For example, if the user follows a link to a resource that no longer exists in the database, Active Record will throw the ActiveRecord::RecordNotFound exception. Rails' default exception handling displays a 500 Server Error message for all exceptions. If the request was made locally, a nice traceback and some added information gets displayed so you can figure out what went wrong and deal with it. If the request was remote Rails will just display a simple "500 Server Error" message to the user, or a "404 Not Found" if there was a routing error or a record could not be found. Sometimes you might want to customize how these errors are caught and how they're displayed to the user. There are several levels of exception handling available in a Rails application:
+
+=== The default 500 and 404 templates ===
+
+By default a production application will render either a 404 or a 500 error message. These messages are contained in static HTML files in the `public` folder, in `404.html` and `500.html` respectively. You can customize these files to add some extra information and layout, but remember that they are static; i.e. you can't use RHTML or layouts in them, just plain HTML.
+
+=== `rescue_from` ===
+
+If you want to do something a bit more elaborate when catching errors, you can use link::http://api.rubyonrails.org/classes/ActionController/Rescue/ClassMethods.html#M000620[rescue_from], which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses. When an exception occurs which is caught by a rescue_from directive, the exception object is passed to the handler. The handler can be a method or a Proc object passed to the `:with` option. You can also use a block directly instead of an explicit Proc object.
+
+Let's see how we can use rescue_from to intercept all ActiveRecord::RecordNotFound errors and do something with them.
+
+[source, ruby]
+-----------------------------------
+class ApplicationController < ActionController::Base
+
+ rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found
+
+private
+
+ def record_not_found
+ render :text => "404 Not Found", :status => 404
+ end
+
+end
+-----------------------------------
+
+Of course, this example is anything but elaborate and doesn't improve the default exception handling at all, but once you can catch all those exceptions you're free to do whatever you want with them. For example, you could create custom exception classes that will be thrown when a user doesn't have access to a certain section of your application:
+
+[source, ruby]
+-----------------------------------
+class ApplicationController < ActionController::Base
+
+ rescue_from User::NotAuthorized, :with => :user_not_authorized
+
+private
+
+ def user_not_authorized
+ flash[:error] = "You don't have access to this section."
+ redirect_to :back
+ end
+
+end
+
+class ClientsController < ApplicationController
+
+ # Check that the user has the right authorization to access clients.
+ before_filter :check_authorization
+
+ # Note how the actions don't have to worry about all the auth stuff.
+ def edit
+ @client = Client.find(params[:id])
+ end
+
+private
+
+ # If the user is not authorized, just throw the exception.
+ def check_authorization
+ raise User::NotAuthorized unless current_user.admin?
+ end
+
+end
+-----------------------------------
+
+NOTE: Certain exceptions are only rescuable from the ApplicationController class, as they are raised before the controller gets initialized and the action gets executed. See Pratik Naik's link:http://m.onkey.org/2008/7/20/rescue-from-dispatching[article] on the subject for more information.
diff --git a/railties/doc/guides/actioncontroller/session.txt b/railties/doc/guides/actioncontroller/session.txt
index 50ed76e3ae..467cffbf85 100644
--- a/railties/doc/guides/actioncontroller/session.txt
+++ b/railties/doc/guides/actioncontroller/session.txt
@@ -1,30 +1,62 @@
== Session ==
-Your application sets up a session for each user which can persist small amounts of data between requests. The session is only available in the controller. It can be stored in a number of different session stores:
-
-TODO: Not sure if all of these are available by default.
+Your application has a session for each user in which you can store small amounts of data that will be persisted between requests. The session is only available in the controller and can use one of a number of different storage mechanisms:
* CookieStore - Stores everything on the client.
- * SQLSessionStore - Stores the data in a database using SQL.
* DRBStore - Stores the data on a DRb client.
* MemCacheStore - Stores the data in MemCache.
* ActiveRecordStore - Stores the data in a database using Active Record.
All session stores store the session id in a cookie - there is no other way of passing it to the server. Most stores also use this key to locate the session data on the server.
-The default and recommended store, the Cookie Store, does not store session data on the server, but in the cookie itself. The data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents. It can only store 4Kb of data - much less than the others - but this is usually enough. Storing large amounts of data is discouraged no matter which session store your application uses. Expecially discouraged is storing complex objects (anything other than basic Ruby objects) in the session, as the server might not be able to reassemble them between requests, which will result in an error. The Cookie Store has the added advantage that it does not require any setting up beforehand - Rails will generate a "secret key" which will be used to sign the cookie when you create the application.
+The default and recommended store, the Cookie Store, does not store session data on the server, but in the cookie itself. The data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents. It can only store about 4kB of data - much less than the others - but this is usually enough. Storing large amounts of data is discouraged no matter which session store your application uses. Expecially discouraged is storing complex objects (anything other than basic Ruby objects, the primary example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error. The Cookie Store has the added advantage that it does not require any setting up beforehand - Rails will generate a "secret key" which will be used to sign the cookie when you create the application.
If you need a different session storage mechanism, you can change it in the `config/environment.rb` file:
[source, ruby]
------------------------------------------
-# Set to one of [:active_record_store, :sql_session_store, :drb_store, :mem_cache_store, :cookie_store]
+# Set to one of [:active_record_store, :drb_store, :mem_cache_store, :cookie_store]
config.action_controller.session_store = :active_record_store
------------------------------------------
+=== Disabling the session ===
+
+Sometimes you don't need a session, and you can turn it off to avoid the unnecessary overhead. To do this, use the link:http://api.rubyonrails.org/classes/ActionController/SessionManagement/ClassMethods.html#M000649[session] class method in your controller:
+
+[source, ruby]
+------------------------------------------
+class ApplicationController < ActionController::Base
+ session :off
+end
+------------------------------------------
+
+You can also turn the session on or off for a single controller:
+
+[source, ruby]
+------------------------------------------
+# The session is turned off by default in ApplicationController, but we
+# want to turn it on for log in/out.
+class LoginsController < ActionController::Base
+ session :on
+end
+------------------------------------------
+
+Or even a single action:
+
+[source, ruby]
+------------------------------------------
+class ProductsController < ActionController::Base
+ session :on, :only => [:create, :update]
+end
+------------------------------------------
+
=== Accessing the session ===
-In your controller you can access the session through the `session` method. Session values are stored using key/value pairs like a hash:
+In your controller you can access the session through the `session` instance method.
+
+NOTE: There are two `session` methods, the class and the instance method. The class method which is described above is used to turn the session on and off while the instance method described below is used to access session values. The class method is used outside of method definitions while the instance methods is used inside methods, in actions or filters.
+
+Session values are stored using key/value pairs like a hash:
[source, ruby]
------------------------------------------
@@ -33,6 +65,8 @@ class ApplicationController < ActionController::Base
private
# Finds the User with the ID stored in the session with the key :current_user_id
+ # This is a common way to do user login in a Rails application; logging in sets the
+ # session value and logging out removes it.
def current_user
@_current_user ||= session[:current_user_id] && User.find(session[:current_user_id])
end
@@ -74,7 +108,7 @@ class LoginsController < ApplicationController
end
------------------------------------------
-To reset the entire session, use `reset_session`.
+To reset the entire session, use link:http://api.rubyonrails.org/classes/ActionController/Base.html#M000855[reset_session].
=== The flash ===
@@ -95,18 +129,18 @@ end
The `destroy` action redirects to the application's `root_url`, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to a display eventual errors or notices from the flash in the application's layout:
-[source, ruby]
------------------------------------------
-<!-- head, etc -->
-<body>
- <% if flash[:notice] -%>
- <p class="notice"><%= flash[:notice] %></p>
- <% end -%>
- <% if flash[:error] -%>
- <p class="error"><%= flash[:error] %></p>
- <% end -%>
- <!-- more content -->
-</body>
+<html>
+ <!-- <head/> -->
+ <body>
+ <% if flash[:notice] -%>
+ <p class="notice"><%= flash[:notice] %></p>
+ <% end -%>
+ <% if flash[:error] -%>
+ <p class="error"><%= flash[:error] %></p>
+ <% end -%>
+ <!-- more content -->
+ </body>
</html>
------------------------------------------
@@ -128,3 +162,24 @@ class MainController < ApplicationController
end
------------------------------------------
+
+==== flash.now ====
+
+By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the `create` action fails to save a resource and you render the `new` template directly, that's not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use `flash.now` in the same way you use the normal `flash`:
+
+[source, ruby]
+------------------------------------------
+class ClientsController < ApplicationController
+
+ def create
+ @client = Client.new(params[:client])
+ if @client.save
+ # ...
+ else
+ flash.now[:error] = "Could not save client"
+ render :action => "new"
+ end
+ end
+
+end
+------------------------------------------
diff --git a/railties/doc/guides/actioncontroller/streaming.txt b/railties/doc/guides/actioncontroller/streaming.txt
index 6026a8c51b..41d56935b9 100644
--- a/railties/doc/guides/actioncontroller/streaming.txt
+++ b/railties/doc/guides/actioncontroller/streaming.txt
@@ -1,6 +1,6 @@
== Streaming and file downloads ==
-Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the "send_data":http://api.rubyonrails.org/classes/ActionController/Streaming.html#M000624 and the "send_file":http://api.rubyonrails.org/classes/ActionController/Streaming.html#M000623 methods, that will both stream data to the client. `send_file` is a convenience method which lets you provide the name of a file on the disk and it will stream the contents of that file for you.
+Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the link:http://api.rubyonrails.org/classes/ActionController/Streaming.html#M000624[send_data] and the link:http://api.rubyonrails.org/classes/ActionController/Streaming.html#M000623[send_file] methods, that will both stream data to the client. `send_file` is a convenience method which lets you provide the name of a file on the disk and it will stream the contents of that file for you.
To stream data to the client, use `send_data`:
@@ -48,15 +48,15 @@ class ClientsController < ApplicationController
end
----------------------------
-NOTE: Be careful when using (or just don't use) "outside" data (params, cookies, etc) to locate the file on disk, as this is a security risk as someone could gain access to files they are not meant to have access to.
+This will read and stream the file 4Kb at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the `stream` option or adjust the block size with the `buffer_size` option.
-NOTE: It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack.
+WARNING: Be careful when using (or just don't use) "outside" data (params, cookies, etc) to locate the file on disk, as this is a security risk as someone could gain access to files they are not meant to have access to.
-This will read and stream the file 4Kb at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the `stream` option or adjust the block size with the `buffer_size` option.
+TIP: It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack.
=== RESTful downloads ===
-While `send_data` works just fine, if you are creating a RESTful application having separate actions for file downloads is a bit ugly. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing "RESTful downloads". Let's try to rewrite the example so that the PDF download is a part of the `show` action:
+While `send_data` works just fine, if you are creating a RESTful application having separate actions for file downloads is usually not necessary. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing "RESTful downloads". Let's try to rewrite the example so that the PDF download is a part of the `show` action:
[source, ruby]
----------------------------
diff --git a/railties/doc/guides/actioncontroller/verification.txt b/railties/doc/guides/actioncontroller/verification.txt
index 129ff7e7b0..39046eee85 100644
--- a/railties/doc/guides/actioncontroller/verification.txt
+++ b/railties/doc/guides/actioncontroller/verification.txt
@@ -1,3 +1,40 @@
== Verification ==
-Describe how to use the verify methods to make sure some prerequisites are met before an action gets run
+Verifications make sure certain criterias are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is present in the `params`, `session` or `flash` hashes or that a certain HTTP method was used or that the request was made using XMLHTTPRequest (Ajax). The default action taken when these criterias are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash messages and HTTP headers to the response. It is described in the link:http://api.rubyonrails.org/classes/ActionController/Verification/ClassMethods.html[API codumentation] as "essentially a special kind of before_filter".
+
+Let's see how we can use verification to make sure the user supplies a username and a password in order to log in:
+
+[source, ruby]
+---------------------------------------
+class LoginsController < ApplicationController
+
+ verify :params => [:username, :password],
+ :render => {:action => "new"},
+ :add_flash => {:error => "Username and password required to log in"}
+
+ def create
+ @user = User.authenticate(params[:username], params[:password])
+ if @user
+ flash[:notice] = "You're logged in"
+ redirect_to root_url
+ else
+ render :action => "new"
+ end
+ end
+
+end
+---------------------------------------
+
+Now the `create` action won't run unless the "username" and "password" parameters are present, and if they're not, an error message will be added to the flash and the "new" action will be rendered. But there's something rather important missing from the verification above: It will be used for *every* action in LoginsController, which is not what we want. You can limit which actions it will be used for with the `:only` and `:except` options just like a filter:
+
+[source, ruby]
+---------------------------------------
+class LoginsController < ApplicationController
+
+ verify :params => [:username, :password],
+ :render => {:action => "new"},
+ :add_flash => {:error => "Username and password required to log in"},
+ :only => :create #Only run this verification for the "create" action
+
+end
+---------------------------------------
diff --git a/railties/doc/guides/actionview/layouts_and_rendering.txt b/railties/doc/guides/actionview/layouts_and_rendering.txt
index 278cca20a6..00f9dbbdd9 100644
--- a/railties/doc/guides/actionview/layouts_and_rendering.txt
+++ b/railties/doc/guides/actionview/layouts_and_rendering.txt
@@ -427,6 +427,15 @@ If you're loading multiple javascript files, you can create a better user experi
-------------------------------------------------------
<%= javascript_include_tag "main", "columns", :cache => true %>
-------------------------------------------------------
+
+By default, the combined file will be delivered as +javascripts/all.js+. You can specify a location for the cached asset file instead:
+
+[source, ruby]
+-------------------------------------------------------
+<%= javascript_include_tag "main", "columns", :cache => 'cache/main/display' %>
+-------------------------------------------------------
+
+You can even use dynamic paths such as "cache/#{current_site}/main/display"+.
==== Linking to CSS Files with +stylesheet_link_tag+
@@ -486,6 +495,15 @@ If you're loading multiple CSS files, you can create a better user experience by
<%= stylesheet_link_tag "main", "columns", :cache => true %>
-------------------------------------------------------
+By default, the combined file will be delivered as +stylesheets/all.css+. You can specify a location for the cached asset file instead:
+
+[source, ruby]
+-------------------------------------------------------
+<%= stylesheet_link_tag "main", "columns", :cache => 'cache/main/display' %>
+-------------------------------------------------------
+
+You can even use dynamic paths such as "cache/#{current_site}/main/display"+.
+
==== Linking to Images with +image_tag+
The +image_tag+ helper builds an HTML +<image>+ tag to the specified file. By default, files are loaded from +public/images+. If you don't specify an extension, .png is assumed by default:
@@ -697,6 +715,7 @@ Rails will render the +_product_ruler+ partial (with no data passed in to it) be
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/15[Lighthouse ticket]
+* October 16, 2008: Ready for publication by link:../authors.html#mgunderloy[Mike Gunderloy]
* October 4, 2008: Additional info on partials (+:object+, +:as+, and +:spacer_template+) by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
* September 28, 2008: First draft by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
diff --git a/railties/doc/guides/activerecord/association_basics.txt b/railties/doc/guides/activerecord/association_basics.txt
index f9ec7a5f55..df89cfb531 100644
--- a/railties/doc/guides/activerecord/association_basics.txt
+++ b/railties/doc/guides/activerecord/association_basics.txt
@@ -354,8 +354,8 @@ In designing a data model, you will sometimes find a model that should have a re
[source, ruby]
-------------------------------------------------------
class Employee < ActiveRecord::Base
- has_many :subordinates, :class_name => :user, :foreign_key => "manager_id"
- belongs_to :manager, :class_name => :user
+ has_many :subordinates, :class_name => "User", :foreign_key => "manager_id"
+ belongs_to :manager, :class_name => "User"
end
-------------------------------------------------------
@@ -636,12 +636,12 @@ The +belongs_to+ association supports these options:
//
===== +:class_name+
-If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if an order belongs to a customer, but the actual name of the model containing customers is patron, you'd set things up this way:
+If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if an order belongs to a customer, but the actual name of the model containing customers is +Patron+, you'd set things up this way:
[source, ruby]
-------------------------------------------------------
class Order < ActiveRecord::Base
- belongs_to :customer, :class_name => :patron
+ belongs_to :customer, :class_name => "Patron"
end
-------------------------------------------------------
@@ -711,7 +711,7 @@ By convention, Rails guesses that the column used to hold the foreign key on thi
[source, ruby]
-------------------------------------------------------
class Order < ActiveRecord::Base
- belongs_to :customer, :class_name => :patron, :foreign_key => "patron_id"
+ belongs_to :customer, :class_name => "Patron", :foreign_key => "patron_id"
end
-------------------------------------------------------
@@ -863,7 +863,7 @@ In many situations, you can use the default behavior of +has_one+ without any cu
[source, ruby]
-------------------------------------------------------
class Supplier < ActiveRecord::Base
- has_one :account, :class_name => :billing, :dependent => :nullify
+ has_one :account, :class_name => "Billing", :dependent => :nullify
end
-------------------------------------------------------
@@ -895,12 +895,12 @@ Setting the +:as+ option indicates that this is a polymorphic association. Polym
===== +:class_name+
-If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a supplier has an account, but the actual name of the model containing accounts is billing, you'd set things up this way:
+If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a supplier has an account, but the actual name of the model containing accounts is Billing, you'd set things up this way:
[source, ruby]
-------------------------------------------------------
class Supplier < ActiveRecord::Base
- has_one :account, :class_name => :billing
+ has_one :account, :class_name => "Billing"
end
-------------------------------------------------------
@@ -1205,12 +1205,12 @@ Setting the +:as+ option indicates that this is a polymorphic association, as di
===== +:class_name+
-If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a customer has many orders, but the actual name of the model containing orders is transactions, you'd set things up this way:
+If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a customer has many orders, but the actual name of the model containing orders is +Transaction+, you'd set things up this way:
[source, ruby]
-------------------------------------------------------
class Customer < ActiveRecord::Base
- has_many :orders, :class_name => :transaction
+ has_many :orders, :class_name => "Transaction"
end
-------------------------------------------------------
@@ -1221,7 +1221,7 @@ The +:conditions+ option lets you specify the conditions that the associated obj
[source, ruby]
-------------------------------------------------------
class Customer < ActiveRecord::Base
- has_many :confirmed_orders, :class_name => :orders, :conditions => "confirmed = 1"
+ has_many :confirmed_orders, :class_name => "Order", :conditions => "confirmed = 1"
end
-------------------------------------------------------
@@ -1230,7 +1230,7 @@ You can also set conditions via a hash:
[source, ruby]
-------------------------------------------------------
class Customer < ActiveRecord::Base
- has_many :confirmed_orders, :class_name => :orders, :conditions => { :confirmed => true }
+ has_many :confirmed_orders, :class_name => "Order", :conditions => { :confirmed => true }
end
-------------------------------------------------------
@@ -1321,7 +1321,7 @@ The +:limit+ option lets you restrict the total number of objects that will be f
[source, ruby]
-------------------------------------------------------
class Customer < ActiveRecord::Base
- has_many :recent_orders, :class_name => :orders, :order => "order_date DESC", :limit => 100
+ has_many :recent_orders, :class_name => "Order", :order => "order_date DESC", :limit => 100
end
-------------------------------------------------------
@@ -1591,19 +1591,19 @@ TIP: The +:foreign_key+ and +:association_foreign_key+ options are useful when s
[source, ruby]
-------------------------------------------------------
class User < ActiveRecord::Base
- has_and_belongs_to_many :friends, :class_name => :users,
+ has_and_belongs_to_many :friends, :class_name => "User",
:foreign_key => "this_user_id", :association_foreign_key => "other_user_id"
end
-------------------------------------------------------
===== +:class_name+
-If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a part has many assemblies, but the actual name of the model containing assemblies is gadgets, you'd set things up this way:
+If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a part has many assemblies, but the actual name of the model containing assemblies is +Gadget+, you'd set things up this way:
[source, ruby]
-------------------------------------------------------
class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :class_name => :gadgets
+ has_and_belongs_to_many :assemblies, :class_name => "Gadget"
end
-------------------------------------------------------
@@ -1654,7 +1654,7 @@ By convention, Rails guesses that the column in the join table used to hold the
[source, ruby]
-------------------------------------------------------
class User < ActiveRecord::Base
- has_and_belongs_to_many :friends, :class_name => :users,
+ has_and_belongs_to_many :friends, :class_name => "User",
:foreign_key => "this_user_id", :association_foreign_key => "other_user_id"
end
-------------------------------------------------------
diff --git a/railties/doc/guides/activerecord/finders.txt b/railties/doc/guides/activerecord/finders.txt
index 2547ae3f26..d1169ffdd4 100644
--- a/railties/doc/guides/activerecord/finders.txt
+++ b/railties/doc/guides/activerecord/finders.txt
@@ -103,6 +103,56 @@ Be aware that `Client.first`/`Client.find(:first)` and `Client.last`/`Client.fin
If you'd like to add conditions to your find, you could just specify them in there, just like `Client.find(:first, :conditions => "orders_count = '2'")`. Now what if that number could vary, say as a parameter from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like `Client.find(:first, :conditions => ["orders_count = ?", params[:orders]])`. ActiveRecord will go through the first element in the conditions value and any additional elements will replace the question marks (?) in the first element. If you want to specify two conditions, you can do it like `Client.find(:first, :conditions => ["orders_count = ? AND locked = ?", params[:orders], false])`. In this example, the first question mark will be replaced with the value in params orders and the second will be replaced with true and this will find the first record in the table that has '2' as its value for the orders_count field and 'false' for its locked field.
+The reason for doing code like:
+
+[source, ruby]
+`Client.find(:first, :conditions => ["orders_count = ?", params[:orders]])`
+
+instead of:
+
+`Client.find(:first, :conditions => "orders_count = #{params[:orders]}")`
+
+is because of parameter safety. Putting the variable directly into the conditions string will parse the variable *as-is*. This means that it will be an unescaped variable directly from a user who may have malicious intent. If you do this, you put your entire database at risk because once a user finds out he or she can exploit your database they can do just about anything to it. Never ever put your parameters directly inside the conditions string.
+
+If you're looking for a range inside of a table for example users created in a certain timeframe you can use the conditions option coupled with the IN sql statement for this. If we had two dates coming in from a controller we could do something like this to look for a range:
+
+[source, ruby]
+Client.find(:all, :conditions => ["created_at IN (?)", (params[:start_date].to_date)..(params[:end_date].to_date)])
+
+This would generate the proper query which is great for small ranges but not so good for larger ranges. For example if you pass in a range of date objects spanning a year that's 365 (or possibly 366, depending on the year) strings it will attempt to match your field against.
+
+[source, sql]
+SELECT * FROM `users` WHERE (created_at IN ('2007-12-31','2008-01-01','2008-01-02','2008-01-03','2008-01-04','2008-01-05','2008-01-06','2008-01-07','2008-01-08','2008-01-09','2008-01-10','2008-01-11','2008-01-12','2008-01-13','2008-01-14','2008-01-15','2008-01-16','2008-01-17','2008-01-18','2008-01-19','2008-01-20','2008-01-21','2008-01-22','2008-01-23',...
+2008-12-15','2008-12-16','2008-12-17','2008-12-18','2008-12-19','2008-12-20','2008-12-21','2008-12-22','2008-12-23','2008-12-24','2008-12-25','2008-12-26','2008-12-27','2008-12-28','2008-12-29','2008-12-30','2008-12-31'))
+
+
+Things can get *really* messy if you pass in time objects as it will attempt to compare your field to *every second* in that range:
+
+[source, ruby]
+Client.find(:all, :conditions => ["created_at IN (?)", (params[:start_date].to_date.to_time)..(params[:end_date].to_date.to_time)])
+
+[source, sql]
+SELECT * FROM `users` WHERE (created_at IN ('2007-12-01 00:00:00', '2007-12-01 00:00:01' ... '2007-12-01 23:59:59', '2007-12-02 00:00:00'))
+
+This could possibly cause your database server to raise an unexpected error, for example MySQL will throw back this error:
+
+[source, txt]
+Got a packet bigger than 'max_allowed_packet' bytes: <query>
+
+Where <query> is the actual query used to get that error.
+
+In this example it would be better to use greater-than and less-than operators in SQL, like so:
+
+[source, ruby]
+Client.find(:all, :condtions => ["created_at > ? AND created_at < ?", params[:start_date], params[:end_date]])
+
+You can also use the greater-than-or-equal-to and less-than-or-equal-to like this:
+
+[source, ruby]
+Client.find(:all, :condtions => ["created_at >= ? AND created_at <= ?", params[:start_date], params[:end_date]])
+
+Just like in Ruby.
+
== Ordering
If you're getting a set of records and want to force an order, you can use `Client.find(:all, :order => "created_at")` which by default will sort the records by ascending order. If you'd like to order it in descending order, just tell it to do that using `Client.find(:all, :order => "created_at desc")`
@@ -133,6 +183,8 @@ SELECT * FROM clients LIMIT 5, 5
== Group
+TODO
+
== Read Only
Readonly is a find option that you can set in order to make that instance of the record read-only. Any attempt to alter or destroy the record will not succeed, raising an `ActiveRecord::ReadOnlyRecord` error. To set this option, specify it like this:
@@ -149,18 +201,26 @@ client.save
== Lock
+If you're wanting to stop race conditions for a specific record, say for example you're incrementing a single field for a record you can use the lock option to ensure that the record is updated correctly. It's recommended this be used inside a transaction.
+
+[source, Ruby]
+Topic.transaction do
+ t = Topic.find(params[:id], :lock => true)
+ t.increment!(:views)
+end
+
== Making It All Work Together
-You can chain these options together in no particular order as ActiveRecord will write the correct SQL for you. For example you could do this: `Client.find(:all, :order => "created_at DESC", :select => "viewable_by, created_at", :conditions => ["viewable_by = ?", params[:level]], :limit => 10), which should execute a query like `SELECT viewable_by, created_at FROM clients WHERE ORDER BY created_at DESC LIMIT 0,10` if you really wanted it.
+You can chain these options together in no particular order as ActiveRecord will write the correct SQL for you. If you specify two instances of the same options inside the find statement ActiveRecord will use the latter.
== Eager Loading
Eager loading is loading associated records along with any number of records in as few queries as possible. Lets say for example if we wanted to load all the addresses associated with all the clients all in the same query we would use `Client.find(:all, :include => :address)`. If we wanted to include both the address and mailing address for the client we would use `Client.find(:all), :include => [:address, :mailing_address]). Inclue will first find the client records and then load the associated address records. Running script/server in one window, and executing the code through script/console in another window, the output should look similar to this:
[source, sql]
-Client Load (0.000383) SELECT \* FROM clients
-Address Load (0.119770) SELECT addresses.\* FROM addresses WHERE (addresses.client_id IN (13,14))
-MailingAddress Load (0.001985) SELECT mailing_addresses.\* FROM mailing_addresses WHERE (mailing_addresses.client_id IN (13,14))
+Client Load (0.000383) SELECT * FROM clients
+Address Load (0.119770) SELECT addresses.* FROM addresses WHERE (addresses.client_id IN (13,14))
+MailingAddress Load (0.001985) SELECT mailing_addresses.* FROM mailing_addresses WHERE (mailing_addresses.client_id IN (13,14))
The numbers `13` and `14` in the above SQL are the ids of the clients gathered from the `Client.find(:all)` query. Rails will then run a query to gather all the addresses and mailing addresses that have a client_id of 13 or 14. Although this is done in 3 queries, this is more efficient than not eager loading because without eager loading it would run a query for every time you called `address` or `mailing_address` on one of the objects in the clients array, which may lead to performance issues if you're loading a large number of records at once.
@@ -168,8 +228,17 @@ An alternative (and more efficient) way to do eager loading is to use the joins
[source, sql]
`Client Load (0.000455) SELECT clients.* FROM clients INNER JOIN addresses ON addresses.client_id = client.id INNER JOIN mailing_addresses ON mailing_addresses.client_id = client.id
+
This query is more efficent, but there's a gotcha. If you have a client who does not have an address or a mailing address they will not be returned in this query at all. If you have any association as an optional association, you may want to use include rather than joins.
+When using eager loading you can specify conditions for the columns of the tables inside the eager loading to get back a smaller subset. If, for example, you want to find a client and all their orders within the last two weeks you could use eager loading with conditions for this:
+
+[source, Ruby]
+
+Client.find(:first, :include => "orders", :conditions => ["orders.created_at >= ? AND orders.created_at <= ?", Time.now - 2.weeks, Time.now])
+
+[source]
+
== Dynamic finders
With every field (also known as an attribute) you define in your table, ActiveRecord provides finder methods for these. If you have a field called `name` on your Client model for example, you get `find_by_name` and `find_all_by_name` for free from ActiveRecord. If you have also have a `locked` field on the client model, you also get `find_by_locked` and `find_all_by_locked`. If you want to find both by name and locked, you can chain these finders together by simply typing and between the fields for example `Client.find_by_name_and_locked('Ryan', true)`. These finders are an excellent alternative to using the conditions option, mainly because it's shorter to type `find_by_name(params[:name])` than it is to type `find(:first, :conditions => ["name = ?", params[:name]])`.
@@ -189,6 +258,15 @@ client = Client.find_or_initialize_by_name('Ryan')
will either assign an existing client object with the name 'Ryan' to the client local variable, or initialize new object similar to calling `Client.new(:name => 'Ryan')`. From here, you can modify other fields in client by calling the attribute setters on it: `client.locked = true` and when you want to write it to the database just call `save` on it.
+== Finding By SQL
+
+If you'd like to use your own SQL to find records a table you can use `find_by_sql`. `find_by_sql` will return an array of objects even if it only returns a single record in it's call to the database. For example you could run this query:
+
+[source, ruby]
+Client.find_by_sql("SELECT * FROM clients INNER JOIN orders ON clients.id = orders.client_id ORDER clients.created_at desc")
+
+`find_by_sql` provides you with a simple way of making custom calls to the database and converting those to objects.
+
== Working with Associations
When you define a has_many association on a model you get the find method and dynamic finders also on that association. This is helpful for finding associated records within the scope of an exisiting record, for example finding all the orders for a client that have been sent and not received by doing something like `Client.find(params[:id]).orders.find_by_sent_and_received(true, false)`. Having this find method available on associations is extremely helpful when using nested controllers.
@@ -237,6 +315,45 @@ end
This will work with `Client.recent(2.weeks.ago)` and `Client.recent` with the latter always returning records with a created_at date between right now and 2 weeks ago.
Remember that named scopes are stackable, so you will be able to do `Client.recent(2.weeks.ago).unlocked` to find all clients created between right now and 2 weeks ago and have their locked field set to false.
+
+== Existance of Objects
+
+If you simply want to check for the existance of the object there's a method called `exists?`. This method will query the database using the same query as find, but instead of returning an object or collection of objects it will return either true or false.
+
+[source, ruby]
+Client.exists?(1)
+
+The above code will check for the existance of a clients table record with the id of 1 and return true if it exists.
+
+[source, ruby]
+Client.exists?(1,2,3)
+# or
+Client.exists?([1,2,3])
+
+`exists?` also takes multiple ids, as shown by the above code, but the catch is that it will return true if any one of those records exists.
+
+Further more, `exists` takes a `conditions` option much like find:
+
+[source, ruby]
+Client.exists?(:conditions => "first_name = 'Ryan'")
+
+== Calculations
+
+=== Count
+
+If you want to see how many records are in your models table you could call `Client.count` and that will return the number. If you want to be more specific and find all the clients with their age present in the database you can use `Client.count(:age)`.
+
+`count` takes conditions much in the same way `exists?` does:
+
+[source, ruby]
+Client.count(:conditions => "first_name = 'Ryan'")
+
+[source, sql]
+SELECT count(*) AS count_all FROM `clients` WHERE (first_name = 1)
+
+== With Scope
+
+TODO
== Credits
@@ -258,3 +375,15 @@ Thanks to Mike Gunderloy for his tips on creating this guide.
1. Did section on limit and offset, as well as section on readonly.
2. Altered formatting so it doesn't look bad.
+
+=== Sunday, 05 October 2008
+1. Extended conditions section to include IN and using operators inside the conditions.
+2. Extended conditions section to include paragraph and example of parameter safety.
+3. Added TODO sections.
+
+=== Monday, 06 October 2008
+1. Added section in Eager Loading about using conditions on tables that are not the model's own.
+
+=== Thursday, 09 October 2008
+1. Wrote section about lock option and tidied up "Making it all work together" section.
+2. Added section on using count.
diff --git a/railties/doc/guides/getting_started_with_rails/getting_started_with_rails.txt b/railties/doc/guides/getting_started_with_rails/getting_started_with_rails.txt
index 3259ef8a45..b6d8203c8b 100644
--- a/railties/doc/guides/getting_started_with_rails/getting_started_with_rails.txt
+++ b/railties/doc/guides/getting_started_with_rails/getting_started_with_rails.txt
@@ -4,114 +4,209 @@ Getting Started With Rails
This guide covers getting up and running with Ruby on Rails. After reading it, you should be familiar with:
* Installing Rails, creating a new Rails application, and connecting your application to a database
-* Understanding the purpose of each folder in the Rails structure
-* Creating a scaffold, and explain what it is creating and why you need each element
-* The basics of model, view, and controller interaction
-* The basics of HTTP and RESTful design
+* The general layout of a Rails application
+* The basic principles of MVC (Model, View Controller) and RESTful design
+* How to quickly generate the starting pieces of a Rails application.
-== How to use this guide
-This guide is designed for beginners who want to get started with a Rails application from scratch. It assumes that you have no prior experience using the framework. However, it is highly recommended that you *familiarize yourself with Ruby before diving into Rails*. Rails isn't going to magically revolutionize the way you write web applications if you have no experience with the language it uses.
+== This Guide Assumes
+
+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:
+
+* The link:http://www.ruby-lang.org/en/downloads/[Ruby] language
+* The link:http://rubyforge.org/frs/?group_id=126[RubyGems] packaging system
+* A working installation of link:http://www.sqlite.org/[SQLite] (preferred), link:http://www.mysql.com/[MySQL], or link:http://www.postgresql.org/[PostgreSQL]
+
+It is highly recommended that you *familiarize yourself with Ruby before diving into Rails*. You will find it much easier to follow what's going on with a Rails application if you understand basic Ruby syntax. Rails isn't going to magically revolutionize the way you write web applications if you have no experience with the language it uses. There are some good free resources on the net for learning Ruby, including:
+
+* link:http://www.humblelittlerubybook.com/[Mr. Neigborly’s Humble Little Ruby Book]
+* link:http://www.rubycentral.com/book/[Programming Ruby]
+* link:http://poignantguide.net/ruby/[Why's (Poignant) Guide to Ruby]
== What is Rails?
-Rails is a web development framework written in the Ruby language. It is designed to make programming web applications easier by making several assumptions about what every developer needs to get started. It allows you to write less code while accomplishing more than other languages and frameworks.
-== Installing Rails
+Rails is a web development framework written in the Ruby language. It is designed to make programming web applications easier by making several assumptions about what every developer needs to get started. It allows you to write less code while accomplishing more than many other languages and frameworks. Longtime Rails developers also report that it makes web application development more fun.
+
+Rails is _opinionated software_. That is, it assumes that there is a best way to do things, and it's designed to encourage that best way - and in some cases discourage alternatives. If you learn "The Rails Way" you'll probably discover a tremendous increase in productivity. If you persist in bringing old habits from other languages to your Rails development, and trying to use patterns you learned elsewhere, you may have a less happy experience.
+
+The Rails philosophy includes several guiding principles:
+
+* DRY - "Don't Repeat Yourself" - suggests that writing the same code over and over again is a bad thing.
+* Convention Over Configuration - means that Rails makes assumptions about what you want to do and how you're going to do it, rather than letting you tweak every little thing through endless configuration files.
+* REST is the best pattern for web applications - organizing your application around resources and standard HTTP verbs is the fastest way to go.
+
+=== The MVC Architecture
+
+Rails is organized around the Model, View, Controller architecture, usually just called MVC. MVC benefits include:
+
+* Isolation of business logic from the user interface
+* Ease of keeping code DRY
+* Making it clear where different types of code belong for easier maintenance
+
+==== Models
+
+A model represents the information (data) of the application and the rules to manipulate that data. In the case of Rails, models are primarily used for managing the rules of interaction with a corresponding database table. In most cases, one table in your database will correspond to one model in your application. The bulk of your application's business logic will be concentrated in the models.
+
+==== Views
+
+Views represent the user interface of your application. In Rails, views are often HTML files with embedded Ruby code that performs tasks related solely to the presentation of the data. Views handle the job of providing data to the web browser or other tool that is used to make requests from your application.
+
+==== Controllers
+
+Controllers provide the "glue" between models and views. In Rails, controllers are responsible for processing the incoming requests from the web browser, interrogating the models for data, and passing that data on to the views for presentation.
+
+=== The Components of Rails
+
+Rails provides a full stack of components for creating web applications, including:
+
+* Action Controller
+* Action View
+* Active Record
+* Action Mailer
+* Active Resource
+* Railties
+* Active Support
+
+==== Action Controller
+
+Action Controller is the component that manages the controllers in a Rails application. The Action Controller framework processes incoming requests to a Rails application, extracts parameters, and dispatches them to the intended action. Services provided by Action Controller include session management, template rendering, and redirect management.
+
+==== Action View
+
+Action View manages the views of your Rails application. It can create both HTML and XML output by default. Action View manages rendering templates, including nested and partial templates, and includes built-in AJAX support.
+
+==== Active Record
+
+Active Record is the base for the models in a Rails application. It provides database independence, basic CRUD functionality, advanced finding capabilities, and the ability to relate models to one another, among other services.
+
+==== Action Mailer
+
+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.
+
+==== Active Resource
+
+Active Resource provides a framework for managing the connection between business objects an RESTful web services. It implements a way to map web-based resources to local objects with CRUD semantics.
+
+==== Railties
+
+Railties is the core Rails code that builds new Rails applications and glues the various frameworks together in any Rails application.
+
+==== Active Support
-`gem install rails`
+Active Support is an extensive collection of utility classes and standard Ruby library extensions that are used in the Rails, both by the core code and by your applications.
-== Create a new Rails project
+=== REST
-We're going to create a Rails project called "blog", which is the project that we will build off of for this guide.
+The foundation of the RESTful architecture is generally considered to be Roy Fielding's doctoral thesis, link:http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm[Architectural Styles and the Design of Network-based Software Architectures]. Fortunately, you need not read this entire document to understand how REST works in Rails. REST, an acronym for Representational State Transfer, boils down to two main principles for our purposes:
-From your terminal, type:
+* Using resource identifiers (which, for the purposes of discussion, you can think of as URLs) to represent resources
+* Transferring representations of the state of that resource between system components.
-`rails blog`
+For example, to a Rails application a request such as this:
-This will create a folder in your working directory called "blog". Open up that folder and have a look at it. For the majority of this tutorial, we will live in the app/ folder, but here's a basic rundown on the function of each folder in a Rails app:
++DELETE /photos/17+
+
+would be understood to refer to a photo resource with the ID of 17, and to indicate a desired action - deleting that resource. REST is a natural style for the architecture of web applications, and Rails makes it even more natural by using conventions to shield you from some of the RESTful complexities.
+
+== Creating a New Rails Project
+
+If you follow this guide, you'll create a Rails project called +blog+, a (very) simple weblog. Before you can start building the application, you need to make sure that you have Rails itself installed.
+
+=== Installing Rails
+
+In most cases, the easiest way to install Rails is to take advantage of RubyGems:
+
+[source, shell]
+-------------------------------------------------------
+$ gem install rails
+-------------------------------------------------------
+
+NOTE: There are some special circumstances in which you might want to use an alternate installation strategy:
+
+* If you're working on Windows, you may find it easier to install link:http://instantrails.rubyforge.org/wiki/wiki.pl[Instant Rails]. Be aware, though, that Instant Rails releases tend to lag seriously behind the actual Rails version. Also, you will find that Rails development on Windows is overall less pleasant than on other operating systems. If at all possible, we suggest that you install a Linux virtual machine and use that for Rails development, instead of using Windows.
+* If you want to keep up with cutting-edge changes to Rails, you'll want to clone the link:http://github.com/rails/rails/tree/master[Rails source code] from github. This is not recommended as an option for beginners, though.
+
+=== Creating the Blog Application
+
+Open a terminal, navigate to a folder where you have rights to create files, and type:
+
+[source, shell]
+-------------------------------------------------------
+$ rails blog
+-------------------------------------------------------
+
+This will create a Rails application that uses a SQLite database for data storage. If you prefer to use MySQL, run this command instead:
+
+[source, shell]
+-------------------------------------------------------
+$ rails blog -d mysql
+-------------------------------------------------------
+
+And if you're using PostgreSQL for data storage, run this command:
+
+[source, shell]
+-------------------------------------------------------
+$ rails blog -d postgresql
+-------------------------------------------------------
+
+In any case, Rails will create a folder in your working directory called +blog+. Open up that folder and explore its contents. Most of the work in this tutorial will happen in the +app/+ folder, but here's a basic rundown on the function of each folder that Rails creates in a new application by default:
[grid="all"]
`-----------`-----------------------------------------------------------------------------------------------------------------------------
File/Folder Purpose
------------------------------------------------------------------------------------------------------------------------------------------
-README This is a brief instruction manual for your application. Use it to tell others what it does, how to set it up, etc.
-Rakefile
-app/ Contains the controllers, models, and views for your application. We'll focus on the app folder in this guide
-config/ Configure your application's runtime rules, routes, database, etc.
-db/ Shows your current database schema, as well as the database migrations (we'll get into migrations shortly)
-doc/ In-depth documentation for your application
-lib/ Extended modules for your application (not covered in this guide)
-log/ Application log files
-public/ The only folder seen to the world as-is. This is where your images, javascript, stylesheets (CSS), and other static files go
-script/ Scripts provided by Rails to do recurring tasks, benchmarking, plugin installation, starting the console or the web server
-test/ Unit tests, fixtures, etc. (not covered in this guide)
-tmp/ Temporary files
-vendor/ Plugins folder
++README+ This is a brief instruction manual for your application. Use it to tell others what your application does, how to set it up, and so on.
++Rakefile+ This file contains batch jobs that can be run from the terminal.
++app/+ Contains the controllers, models, and views for your application. You'll focus on this folder for the remainder of this guide.
++config/+ Configure your application's runtime rules, routes, database, and more.
++db/+ Shows your current database schema, as well as the database migrations. You'll learn about migrations shortly.
++doc/+ In-depth documentation for your application.
++lib/+ Extended modules for your application (not covered in this guide).
++log/+ Application log files.
++public/+ The only folder seen to the world as-is. This is where your images, javascript, stylesheets (CSS), and other static files go.
++script/+ Scripts provided by Rails to do recurring tasks, such as benchmarking, plugin installation, and starting the console or the web server.
++test/+ Unit tests, fixtures, and other test apparatus. These are covered in link:../testing_rails_applications/testing_rails_applications.html[Testing Rails Applications]
++tmp/+ Temporary files
++vendor/+ A place for third-party code. In a typical Rails application, this includes Ruby Gems, the Rails source code (if you install it into your project) and plugins containing additional prepackaged functionality.
-------------------------------------------------------------------------------------------------------------------------------------------
-=== Configure SQLite Database
+=== Configuring a Database
-Rails comes with built-in support for SQLite, which is a lightweight flat-file based database application. While it is not designed for a production environment, it works well for development and testing. Rails defaults to SQLite as the database adapter when creating a new project, but you can always change it later.
+Just about every Rails application will interact with a database. The database to use is specified in a configuration file, +config/database.yml+.
+If you open this file in a new Rails application, you'll see a default database configuration using SQLite. The file contains sections for three different environments in which Rails can run by default:
-Open up +config/database.yml+ and you'll see the following:
+* The +development+ environment is used on your development computer as you interact manually with the application
+* The +test+ environment is used to run automated tests
+* The +production+ environment is used when you deploy your application for the world to use.
---------------------------------------------------------------------
-# SQLite version 3.x
-# gem install sqlite3-ruby (not necessary on OS X Leopard)
+==== Configuring a SQLite Database
+
+Rails comes with built-in support for SQLite, which is a lightweight flat-file based database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using a SQLite database when creating a new project, but you can always change it later.
+
+Here's the section of the default configuration file with connection information for the development environment:
+
+[source, ruby]
+-------------------------------------------------------
development:
adapter: sqlite3
database: db/development.sqlite3
timeout: 5000
+-------------------------------------------------------
-# Warning: The database defined as "test" will be erased and
-# re-generated from your development database when you run "rake".
-# Do not set this db to the same as development or production.
-test:
- adapter: sqlite3
- database: db/test.sqlite3
- timeout: 5000
-
-production:
- adapter: sqlite3
- database: db/production.sqlite3
- timeout: 5000
---------------------------------------------------------------------
+If you don't have any database set up, SQLite is the easiest to get installed. If you're on OS X 10.5 or greater on a Mac, you already have it. Otherwise, you can install it using RubyGems:
If you're not running OS X 10.5 or greater, you'll need to install the SQLite gem. Similar to installing Rails you just need to run:
-`gem install sqlite3-ruby`
+[source, shell]
+-------------------------------------------------------
+$ gem install sqlite3-ruby
+-------------------------------------------------------
-Because we're using SQLite, there's really nothing else you need to do to setup your database!
+==== Configuring a MySQL Database
-=== Configure MySQL Database
+If you choose to use MySQL, your +config/database.yml+ will look a little different. Here's the development section:
-.MySQL Tip
-*******************************
-If you want to skip directly to using MySQL on your development machine, typing the following will get you setup with a MySQL configuration file that assumes MySQL is running locally and that the root password is blank:
-
-`rails blog -d mysql`
-
-You'll need to make sure you have MySQL up and running on your system with the correct permissions. MySQL installation and configuration is outside the scope of this document.
-*******************************
-
-If you choose to use MySQL, your +config/database.yml+ will look a little different:
-
---------------------------------------------------------------------
-# MySQL. Versions 4.1 and 5.0 are recommended.
-#
-# Install the MySQL driver:
-# gem install mysql
-# On Mac OS X:
-# sudo gem install mysql -- --with-mysql-dir=/usr/local/mysql
-# On Mac OS X Leopard:
-# sudo env ARCHFLAGS="-arch i386" gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config
-# This sets the ARCHFLAGS environment variable to your native architecture
-# On Windows:
-# gem install mysql
-# Choose the win32 build.
-# Install MySQL and put its /bin directory on your path.
-#
-# And be sure to use new-style password hashing:
-# http://dev.mysql.com/doc/refman/5.0/en/old-client.html
+[source, ruby]
+-------------------------------------------------------
development:
adapter: mysql
encoding: utf8
@@ -119,92 +214,144 @@ development:
username: root
password:
socket: /tmp/mysql.sock
+-------------------------------------------------------
+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.
-# Warning: The database defined as "test" will be erased and
-# re-generated from your development database when you run "rake".
-# Do not set this db to the same as development or production.
-test:
- adapter: mysql
- encoding: utf8
- database: blog_test
- username: root
- password:
- socket: /tmp/mysql.sock
+==== Configuring a PostgreSQL Database
-production:
- adapter: mysql
- encoding: utf8
- database: blog_production
- username: root
+If you choose to use PostgreSQL, your +config/database.yml+ will be customized to use PostgreSQL databases:
+
+[source, ruby]
+-------------------------------------------------------
+development:
+ adapter: postgresql
+ encoding: unicode
+ database: blog_development
+ username: blog
password:
- socket: /tmp/mysql.sock
-----------------------------------------------------------------------
+-------------------------------------------------------
-== Starting the web server
-Rails comes bundled with the lightweight Webrick web server, which (like SQLite) works great in development mode, but is not designed for a production environment. If you install Mongrel with `gem install mongrel`, Rails will use the Mongrel web server as the default instead (recommended).
-*******************
-If you're interested in alternative web servers for development and/or production, check out mod_rails (a.k.a Passenger)
-*******************
-Rails lets you run in development, test, and production environments (you can also add an unlimited number of additional environments if necessary). In this guide, we're going to work with the development environment only, which is the default when starting the server. From the root of your application folder, simply type the following to startup the web server:
+Change the username and password in the +development+ section as appropriate.
-`./script/server`
+== Hello, Rails!
-This will start a process that allows you to connect to your application via a web browser on port 3000. Open up a browser to +http://localhost:3000/+
+One of the traditional places to start with a new language is by getting some text up on screen quickly. To do that in Rails, you need to create at minimum a controller and a view. Fortunately, you can do that in a single command. Enter this command in your terminal:
-You can hit Ctrl+C anytime from the terminal to stop the web server.
+[source, shell]
+-------------------------------------------------------
+$ script/generate controller home index
+-------------------------------------------------------
-You should see the "Welcome Aboard" default Rails screen, and can click on the "About your application's environment" link to see a brief summary of your current configuration. If you've gotten this far, you're riding rails! Let's dive into the code!
+TIP: If you're on Windows, or your Ruby is set up in some non-standard fashion, you may need to explicitly pass Rails +script+ commands to Ruby: +ruby script/generate controller home index+.
-== Models, Views, and Controllers
-Rails uses Model, View, Controller (MVC) architecture because it isolates business logic from the user interface, ensuring that changes to a template will not affect the underlying code that makes it function. It also helps keep your code clean and DRY (Don't Repeat Yourself!) by making it perfectly clear where different types of code belong.
+Rails will create several files for you, including +app/views/home/index.html.erb+. This is the template that will be used to display the results of the +index+ action (method) in the +home+ controller. Open this file in your text editor and edit it to contain a single line of code:
-=== The Model
-The model represents the information (data) of the application and the rules to manipulate that data. In the case of Rails, models are primarily used for managing the rules of interaction with a corresponding database table. Assume that for every table in your database, you will have a corresponding model (not necessarily the other way around, but that's beyond the scope of this guide).
+[source, html]
+-------------------------------------------------------
+<h1>Hello, Rails!</h1>
+-------------------------------------------------------
-Models in Rails use a singular name, and their corresponding database tables use a plural name. In the case of our "Blog" application, we're going to need a table for our blog posts. Because we're generating a model, we want to use the singular name:
+=== Starting up the Web Server
-`./script/generate model Post`
+You actually have a functional Rails application already - after running only two commands! To see it, you need to start a web server on your development machine. You can do this by running another command:
-You'll see that this generates several files, we're going to focus on two. First, let's take a look at +app/models/post.rb+
+[source, shell]
+-------------------------------------------------------
+$ script/server
+-------------------------------------------------------
--------------------------------
-class Post < ActiveRecord::Base
-end
--------------------------------
+This will fire up the lightweight Webrick web server by default. To see your application in action, open a browser window and navigate to +http://localhost:3000+. You should see Rails' default information page:
-This is what each model you create will look like by default. Here Rails is making the assumption that your Post model will be tied to a database, because it is telling the Post class to descend from the ActiveRecord::Base class, which is where all the database magic happens. Let's leave the model alone for now and move onto migrations.
+image:images/rails_welcome.png[Welcome Aboard screenshot]
-==== Migrations
-Database migrations make it simple to add/remove/modify tables, columns, and indexes while allowing you to roll back or forward between states with ease.
+TIP: To stop the web server, hit Ctrl+C in the terminal window where it's running. In development mode, Rails does not generally require you to stop the server; changes you make in files will be automatically picked up by the server.
-Have a look at +db/migrate/2008XXXXXXXXXX_create_posts.rb+ (Yours will have numbers specific to the time that the file was generated), which was generated when creating our Post model:
+The "Welcome Aboard" page is the smoke test for a new Rails application: it makes sure that you have your software configured correctly enough to serve a page. To view the page you just created, navigate to +http://localhost:3000/home/index+.
--------------------------------------------
-class CreatePosts < ActiveRecord::Migration
- def self.up
- create_table :posts do |t|
+=== Setting the Application Home Page
- t.timestamps
- end
- end
+You'd probably like to replace the "Welcome Aboard" page with your own application's home page. The first step to doing this is to delete the default page from your application:
- def self.down
- drop_table :posts
- end
-end
--------------------------------------------
+[source, shell]
+-------------------------------------------------------
+$ rm public/index.html
+-------------------------------------------------------
+
+Now, you have to tell Rails where your actual home page is located. Open the file +config/routes.rb+ in your editor. This is your application's, _routing file_, which holds entries in a special DSL (domain-specific language) that tells Rails how to connect incoming requests to controllers and actions. At the bottom of the file you'll see the _default routes_:
+
+[source, ruby]
+-------------------------------------------------------
+map.connect ':controller/:action/:id'
+map.connect ':controller/:action/:id.:format'
+-------------------------------------------------------
+
+The default routes handle simple requests such as +/home/index+: Rails translates that into a call to the +index+ action in the +home+ controller. As another example, +/posts/edit/1+ would run the +edit+ action in the +posts+ controller with an +id+ of 1.
+
+To hook up your home page, you need to add another line to the routing file, above the default routes:
+
+[source, ruby]
+-------------------------------------------------------
+map.root :controller => "home"
+-------------------------------------------------------
+
+This line illustrates one tiny bit of the "convention over configuration" approach: if you don't specify an action, Rails assumes the +index+ action.
+
+Now if you navigate to +http://localhost:3000+ in your browser, you'll see the +home/index+ view.
+
+NOTE: For more information about routing, refer to link:../routing/routing_outside_in.html[Rails Routing from the Outside In].
+
+== Getting Up and Running Quickly With Scaffolding
+
+Rails _scaffolding_ is a quick way to generate some of the major pieces of an application. If you want to create the models, views, and controllers for a new resource in a single operation, scaffolding is the tool for the job.
+
+== Creating a Resource
-By default, Rails creates a database migration that will create the table for "posts" (plural name of model). The +create_table+ method takes a ruby block, and by default you'll see +t.timestamps+ in there, which automatically creates and automatically handles +created_at+ and +updated_at+ datetime columns. The +self.up+ section handles progression of the database, whereas the +self.down+ handles regression (or rollback) of the migration.
+In the case of the blog application, you can start by generating a scaffolded Post resource: this will represent a single blog posting. To do this, enter this command in your terminal:
-Let's add some more columns to our migration that suit our post table. We'll create a +name+ column for the person who wrote the post, a +title+ column for the title of the post, and a +content+ column for the actual post content.
+[source, shell]
+-------------------------------------------------------
+$ script/generate scaffold Post name:string title:string content:text
+-------------------------------------------------------
--------------------------------------------
+NOTE: While scaffolding will get you up and running quickly, the "one size fits all" code that it generates is unlikely to be a perfect fit for your application. In most cases, you'll need to customize the generated code. Many experienced Rails developers avoid scaffolding entirely, preferring to write all or most of their source code from scratch.
+
+The scaffold generator will build 13 files in your application, along with some folders, and edit one more. Here's a quick overview of what it creates:
+
+[grid="all"]
+`---------------------------------------------`--------------------------------------------------------------------------------------------
+File Purpose
+------------------------------------------------------------------------------------------------------------------------------------------
+app/models/post.rb The Post model
+db/migrate/20081013124235_create_posts.rb Migration to create the posts table in your database (your name will include a different timestamp)
+app/views/posts/index.html.erb A view to display an index of all posts
+app/views/posts/show.html.erb A view to display a single post
+app/views/posts/new.html.erb A view to create a new post
+app/views/posts/edit.html.erb A view to edit an existing post
+app/views/layouts/posts.html.erb A view to control the overall look and feel of the other posts views
+public/stylesheets/scaffold.css Cascading style sheet to make the scaffolded views look better
+app/controllers/posts_controller.rb The Posts controller
+test/functional/posts_controller_test.rb Functional testing harness for the posts controller
+app/helpers/posts_helper.rb Helper functions to be used from the posts views
+config/routes.rb Edited to include routing information for posts
+test/fixtures/posts.yml Dummy posts for use in testing
+test/unit/post_test.rb Unit testing harness for the posts model
+-------------------------------------------------------------------------------------------------------------------------------------------
+
+=== Running a Migration
+
+One of the products of the +script/generate scaffold+ command is a _database migration_. Migrations are Ruby classes that are designed to make it simple to create and modify database tables. Rails uses rake commands to run migrations, and it's possible to undo a migration after it's been applied to your database. Migration filenames include a timestamp to ensure that they're processed in the order that they were created.
+
+If you look in the +db/migrate/20081013124235_create_posts.rb+ file (remember, yours will have a slightly different name), here's what you'll find:
+
+[source, ruby]
+-------------------------------------------------------
class CreatePosts < ActiveRecord::Migration
def self.up
create_table :posts do |t|
- t.string :name
- t.string :title
- t.text :content
+ t.string :name
+ t.string :title
+ t.text :content
+
t.timestamps
end
end
@@ -213,77 +360,107 @@ class CreatePosts < ActiveRecord::Migration
drop_table :posts
end
end
--------------------------------------------
+-------------------------------------------------------
-Now that we have our migration just right, we can run the migration (the +self.up+ portion) by returning to the terminal and running:
+If you were to translate that into words, it says something like: when this migration is run, create a table named +posts+ with two string columns (+name+ and +title+) and a text column (+content+), and generate timestamp fields to track record creation and updating. You can learn the detailed syntax for migrations in the link:../migrations/migrations.html[Rails Database Migrations] guide.
-`rake db:migrate`
+At this point, you need to do two things: create the database and run the migration. You can use rake commands at the terminal for both of those tasks:
-This command will always run any migrations that have not yet been run.
+[source, shell]
+-------------------------------------------------------
+$ rake db:create
+$ rake db:migrate
+-------------------------------------------------------
-.Singular and Plural Inflections
-**************************************************************************************************************
-Rails is very smart, it knows that if you have a model "Person," the database table should be called "people". If you have a model "Company", the database table will be called "companies". There are a few circumstances where it will not know the correct singular and plural of a model name, but you should have no problem with this as long as you are using common English words. Fixing these rare circumstances is beyond the scope of this guide.
-**************************************************************************************************************
+NOTE: Because you're working in the development environment by default, both of these commands will apply to the database defined in the +development+ section of your +config/database.yml+ file.
-=== The Controller
-The controller communicates input from the user (the view) to the model.
+=== Adding a Link
-==== RESTful Design
-The REST idea will likely take some time to wrap your brain around if you're new to the concept. But know the following:
+To hook the posts up to the home page you've already created, you can add a link to the home page. Open +/app/views/home/index.html.erb+ and modify it as follows:
-* It is best to keep your controllers RESTful at all times if possible
-* Resources must be defined in +config/routes.rb+ in order for the RESTful architecture to work properly, so let's add that now:
+[source, ruby]
+-------------------------------------------------------
+<h1>Hello, Rails!</h1>
---------------------
-map.resources :posts
---------------------
+<%= link_to "My Blog", posts_path %>
+-------------------------------------------------------
-* The seven actions that are automatically part of the RESTful design in Rails are +index+, +show+, +new+, +create+, +edit+, +update+, and +destroy+.
+The +link_to+ method is one of Rails' built-in view helpers. It creates a hyperlink based on text to display and where to go - in this case, to the path for posts.
-Let's generate a controller:
+=== Working with Posts in the Browser
-`./script/generate controller Posts`
+Now you're ready to start working with posts. To do that, navigate to +http://localhost:3000+ and then click the "My Blog" link:
-Open up the controller that it generates in +app/controllers/posts_controller.rb+. It should look like:
+image:images/posts_index.png[Posts Index screenshot]
----------------------------------------------
-class PostsController < ApplicationController
-end
----------------------------------------------
+This is the result of Rails rendering the +index+ view of your posts. There aren't currently any posts in the database, but if you click the +New Post+ link you can create one. After that, you'll find that you can edit posts, look at their details, or destroy them. All of the logic and HTML to handle this was built by the single +script/generate scaffold+ command.
+
+TIP: In development mode (which is what you're working in by default), Rails reloads your application with every browser request, so there's no need to stop and restart the web server.
+
+Congratulations, you're riding the rails! Now it's time to see how it all works.
+
+=== The Model
+
+The model file, +app/models/post.rb+ is about as simple as it can get:
-Because of the +map.resources :posts+ line in your +config/routes.rb+ file, this controller is ready to take on all seven actions listed above. But we're going to need some logic in this controller in order to interact with the model, and we're going to need to generate our view files so the user can interact with your application from their browser.
+[source, ruby]
+-------------------------------------------------------
+class Post < ActiveRecord::Base
+end
+-------------------------------------------------------
-We're going to use the scaffold generator to create all the files and basic logic to make this work, now that you know how to generate models and controllers manually.
+There isn't much to this file - but note that the +Post+ class inherits from +ActiveRecord::Base+. Active Record supplies a great deal of functionality to your Rails models for free, including basic database CRUD (Create, Read, Update, Destroy) operations, data validation, as well as sophisticated search support and the ability to relate multiple models to one another.
-To do that, let's completely start over. Back out of your Rails project folder, and *remove it completely* (`rm -rf blog`).
-Create the project again and enter the directory by running the commands:
+=== Adding Some Validation
-`rails blog`
+Rails includes methods to help you validate the data that you send to models. Open the +app/models/post.rb+ file and edit it:
-`cd blog`
+[source, ruby]
+-------------------------------------------------------
+class Comment < ActiveRecord::Base
+ belongs_to :post
+ validates_presence_of :commenter, :body
+ validates_length_of :commenter, :minimum => 5
+end
+-------------------------------------------------------
+These changes will ensure that all comments have a body and a commenter, and that the commenter is at least five characters long. Rails can validate a variety of conditions in a model, including the presence or uniqueness of columns, their format, and the existence of associated objects.
-=== Rails Scaffold
-Whenever you are dealing with a resource and you know you'll need a way to manage that resource in your application, you can start by generating a scaffold. The reason that this guide did not start with generating the scaffold is because it is not all that useful once you are using Rails on a regular basis. For our blog, we want a "Post" resource, so let's generate that now:
+=== Using the Console
-`./script/generate scaffold Post name:string title:string content:text`
+To see your validations in action, you can use the console. The console is a command-line tool that lets you execute Ruby code in the context of your application:
-This generates the model, controller, migration, views, tests, and routes for this resource. It also populates these files with default data to get started.
+[source, shell]
+-------------------------------------------------------
+$ script/console
+-------------------------------------------------------
-First, let's make sure our database is up to date by running `rake db:migrate`. That may generate an error if your database still has the tables from our earlier migration. In this case, let's completely reset the database and run all migrations by running `rake db:reset`.
+After the console loads, you can use it to work with your application's models:
-Start up the web server with `./script/server` and point your browser to `http://localhost:3000/posts`.
+[source, shell]
+-------------------------------------------------------
+>> c = Comment.create(:body => "A new comment")
+=> #<Comment id: nil, commenter: nil, body: "A new comment",
+post_id: nil, created_at: nil, updated_at: nil>
+>> c.save
+=> false
+>> c.errors
+=> #<ActiveRecord::Errors:0x227be7c @base=#<Comment id: nil,
+commenter: nil, body: "A new comment", post_id: nil, created_at: nil,
+updated_at: nil>, @errors={"commenter"=>["can't be blank",
+"is too short (minimum is 5 characters)"]}>
+-------------------------------------------------------
-Here you'll see an example of the instant gratification of Rails where you can completely manage the Post resource. You'll be able to create, edit, and delete blog posts with ease. Go ahead, try it out.
+This code shows creating a new +Comment+ instance, attempting to save it and getting +false+ for a return value (indicating that the save failed), and inspecting the +errors+ of the comment.
-Now let's see how all this works. Open up `app/controllers/posts_controller.rb`, and you'll see this time it is filled with code.
+TIP: Unlike the development web server, the console does not automatically load your code afresh for each line. If you make changes, type +reload!+ at the console prompt to load them.
-==== Index
+=== Listing All Posts
-Let's take a look at the `index` action:
+The easiest place to start looking at functionality is with the code that lists all posts. Open the file +app/controllers/posts_controller.rb + and look at the +index+ action:
------------------------------------------
+[source, ruby]
+-------------------------------------------------------
def index
@posts = Post.find(:all)
@@ -292,34 +469,83 @@ def index
format.xml { render :xml => @posts }
end
end
------------------------------------------
+-------------------------------------------------------
-In this action, we're setting the `@posts` instance variable to a hash of all posts in the database. `Post.find(:all)` or `Post.all` (in Rails 2.1) calls on our model to return all the Posts in the database with no additional conditions.
+This code sets the +@posts+ instance variable to an array of all posts in the database. +Post.find(:all)+ or +Post.all+ calls the +Post+ model to return all of the posts that are currently in the database, with no limiting conditions.
-The `respond_to` block handles both HTML and XML calls to this action. If we call `http://localhost:3000/posts.xml`, we'll see all our posts in XML format. The HTML format looks for our corresponding view in `app/views/posts/index.html.erb`. You can add any number of formats to this block to allow actions to be processed with different file types.
+TIP: For more information on finding records with Active Record, see link:../activerecord/finders.html[Active Record Finders].
-==== Show
+The +respond_to+ block handles both HTML and XML calls to this action. If you borwse to +http://localhost:3000/posts.xml+, you'll see all of the posts in XML format. The HTML format looks for a view in +app/views/posts/+ with a name that corresponds to the action name. Rails makes all of the instance variables from the action available to the view. Here's +app/view/posts/index.html.erb+:
-Back in your browser, click on the "New post" link and create your first post if you haven't done so already. Return back to the index, and you'll see the details of your post listed, along with three actions to the right of the post: `show`, `edit`, and `destroy`. Click the `show` link, which will bring you to the URL `http://localhost:3000/posts/1`. Now let's look at the `show` action in `app/controllers/posts_controller.rb`:
+[source, ruby]
+-------------------------------------------------------
+<h1>Listing posts</h1>
------------------------------------------
-def show
- @post = Post.find(params[:id])
+<table>
+ <tr>
+ <th>Name</th>
+ <th>Title</th>
+ <th>Content</th>
+ </tr>
- respond_to do |format|
- format.html # show.html.erb
- format.xml { render :xml => @post }
- end
-end
------------------------------------------
+<% for post in @posts %>
+ <tr>
+ <td><%=h post.name %></td>
+ <td><%=h post.title %></td>
+ <td><%=h post.content %></td>
+ <td><%= link_to 'Show', post %></td>
+ <td><%= link_to 'Edit', edit_post_path(post) %></td>
+ <td><%= link_to 'Destroy', post, :confirm => 'Are you sure?', :method => :delete %></td>
+ </tr>
+<% end %>
+</table>
+
+<br />
+
+<%= link_to 'New post', new_post_path %>
+-------------------------------------------------------
+
+This view iterates over the contents of the +@posts+ array to display content and links. A few things to note in the view:
+
+* +h+ is a Rails helper method to sanitize displayed data, preventing cross-site scripting attacks
+* +link_to+ builds a hyperlink to a particular destination
+* +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.
+
+TIP: For more details on the rendering process, see link:../actionview/layouts_and_rendering.html[Layouts and Rendering in Rails].
+
+=== Customizing the Layout
-This time, we're setting `@post` to a single record in the database that is searched for by its `id`, which is provided to the controller by the "1" in `http://localhost:3000/posts/1`. The `show` action is ready to handle HTML or XML with the `respond_to` block: XML can be accessed at: `http://localhost:3000/posts/1.xml`.
+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 +script/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:
-==== New & Create
+[source, ruby]
+-------------------------------------------------------
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-In your controller, you'll see the `new` and `create` actions, which are used together to create a new record. Our `new` action simply instantiates a new Post object without any parameters:
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<head>
+ <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
+ <title>Posts: <%= controller.action_name %></title>
+ <%= stylesheet_link_tag 'scaffold' %>
+</head>
+<body style="background: #EEEEEE;">
------------------------------------------
+<p style="color: green"><%= flash[:notice] %></p>
+
+<%= yield %>
+
+</body>
+</html>
+-------------------------------------------------------
+
+Now when you refresh the +/posts+ page, you'll see a gray background to the page. This same gray background will be used throughout all the views for posts.
+
+=== Creating New Posts
+
+Creating a new post involves two actions. The first is the +new+ action, which instantiates an empty +Post+ object:
+
+[source, ruby]
+-------------------------------------------------------
def new
@post = Post.new
@@ -328,16 +554,45 @@ def new
format.xml { render :xml => @post }
end
end
-----------------------------------------
+-------------------------------------------------------
+
+The +new.html.erb+ view displays this empty Post to the user:
+
+[source, ruby]
+-------------------------------------------------------
+<h1>New post</h1>
-Our `create` action, on the other hand, instantiates a new Post object while setting its attributes to the parameters that we specify in our form. It then uses a `flash[:notice]` to inform the user of the status of the action. If the Post is saved successfully, the action will redirect to the `show` action containing our new Post simply by calling the simple `redirect_to(@post)`.
+<% form_for(@post) do |f| %>
+ <%= f.error_messages %>
-.The Flash
-**************************************************************************************************************
-Rails provides the Flash so that messages can be carried over to another action, providing the user with useful information on the status of their request. In our `create` example, the user never actually sees any page rendered during the Post creation process, because it immediately redirects to the new Post as soon as the record is saved. The Flash allows us to carry over a message to the next action, so once the user is redirected back to the `show` action, they are presented with a message saying "Post was successfully created."
-**************************************************************************************************************
+ <p>
+ <%= f.label :name %><br />
+ <%= f.text_field :name %>
+ </p>
+ <p>
+ <%= f.label :title %><br />
+ <%= f.text_field :title %>
+ </p>
+ <p>
+ <%= f.label :content %><br />
+ <%= f.text_area :content %>
+ </p>
+ <p>
+ <%= f.submit "Create" %>
+ </p>
+<% end %>
-----------------------------------------
+<%= link_to 'Back', posts_path %>
+-------------------------------------------------------
+
+The +form_for+ block is used to create an HTML form. Within this block, you have access to methods to build various controls on the form. For example, +f.text_field :name+ tells Rails to create a text input on the form, and to hook it up to the +name+ attribute of the instance being displayed. You can only use these methods with attributes of the model that the form is based on (in this case +name+, +title+, and +content+). Rails uses +form_for+ in preference to having your write raw HTML because the code is more succinct, and because it explicitly ties the form to a particular model instance.
+
+TIP: If you need to create an HTML form that displays arbitrary fields, not tied to a model, you should use the +form_tag+ method, which provides shortcuts for building forms that are not necessarily tied to a model instance.
+
+When the user clicks the +Create+ button on this form, the browser will send information back to the +create+ method of the controller (Rails knows to call the +create+ method because the form is sent with an HTTP POST request; that's one of the conventions that I mentioned earlier):
+
+[source, ruby]
+-------------------------------------------------------
def create
@post = Post.new(params[:post])
@@ -352,20 +607,493 @@ def create
end
end
end
----------------------------------------
+-------------------------------------------------------
+
+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 saving the new post, it uses +flash[:notice]+ to create an informational message for the user, and redirects to the show action for the post. If there's any problem, the +create+ action just shows the +new+ view a second time, with any error messages.
+
+Rails provides the +flash+ hash (usually just called the Flash) so that messages can be carried over to another action, providing the user with useful information on the status of their request. In the case of +create+, the user never actually sees any page rendered during the Post creation process, because it immediately redirects to the new Post as soon Rails saves the record. The Flash carries over a message to the next action, so that when the user is redirected back to the +show+ action, they are presented with a message saying "Post was successfully created."
+
+=== Showing an Individual Post
+
+When you click the +show+ link for a post on the index page, it will bring you to a URL like +http://localhost:3000/posts/1+. Rails interprets this as a call to the +show+ action for the resource, and passes in +1+ as the +:id+ parameter. Here's the +show+ action:
+
+[source, ruby]
+-------------------------------------------------------
+def show
+ @post = Post.find(params[:id])
+
+ respond_to do |format|
+ format.html # show.html.erb
+ format.xml { render :xml => @post }
+ end
+end
+-------------------------------------------------------
+
+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+:
+
+[source, ruby]
+-------------------------------------------------------
+<p>
+ <b>Name:</b>
+ <%=h @post.name %>
+</p>
+
+<p>
+ <b>Title:</b>
+ <%=h @post.title %>
+</p>
+
+<p>
+ <b>Content:</b>
+ <%=h @post.content %>
+</p>
+
+
+<%= link_to 'Edit', edit_post_path(@post) %> |
+<%= link_to 'Back', posts_path %>
+-------------------------------------------------------
+
+=== Editing Posts
+
+Like creating a new post, editing a post is a two-part process. The first step is a request to +edit_post_path(@post)+ with a particular post. This calls the +edit+ action in the controller:
+
+[source, ruby]
+-------------------------------------------------------
+def edit
+ @post = Post.find(params[:id])
+end
+-------------------------------------------------------
+
+After finding the requested post, Rails uses the +edit.html.erb+ view to display it:
+
+[source, ruby]
+-------------------------------------------------------
+<h1>Editing post</h1>
+
+<% form_for(@post) do |f| %>
+ <%= f.error_messages %>
+
+ <p>
+ <%= f.label :name %><br />
+ <%= f.text_field :name %>
+ </p>
+ <p>
+ <%= f.label :title %><br />
+ <%= f.text_field :title %>
+ </p>
+ <p>
+ <%= f.label :content %><br />
+ <%= f.text_area :content %>
+ </p>
+ <p>
+ <%= f.submit "Update" %>
+ </p>
+<% end %>
+
+<%= link_to 'Show', @post %> |
+<%= link_to 'Back', posts_path %>
+-------------------------------------------------------
+
+Submitting the form created by this view will invoke the +update+ action within the controller:
+
+[source, ruby]
+-------------------------------------------------------
+def update
+ @post = Post.find(params[:id])
+
+ respond_to do |format|
+ if @post.update_attributes(params[:post])
+ flash[:notice] = 'Post was successfully updated.'
+ format.html { redirect_to(@post) }
+ format.xml { head :ok }
+ else
+ format.html { render :action => "edit" }
+ format.xml { render :xml => @post.errors, :status => :unprocessable_entity }
+ end
+ end
+end
+-------------------------------------------------------
+
+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.
+
+NOTE: Sharp-eyed readers will have noticed that the +form_for+ declaration is identical for the +create+ and +edit+ views. Rails generates different code for the two forms because it's smart enough to notice that in the one case it's being passed a new record that has never been saved, and in the other case an existing record that has already been saved to the database. In a production Rails application, you would ordinarily eliminate this duplication by moving identical code to a _partial template_, which you could then include in both parent templates. But the scaffold generator tries not to make too many assumptions, and generates code that’s easy to modify if you want different forms for +create+ and +edit+.
+
+=== Destroying a Post
+
+Finally, clicking one of the +destroy+ links sends the associated id to the +destroy+ action:
+
+[source, ruby]
+-------------------------------------------------------
+def destroy
+ @post = Post.find(params[:id])
+ @post.destroy
+
+ respond_to do |format|
+ format.html { redirect_to(posts_url) }
+ format.xml { head :ok }
+ end
+end
+-------------------------------------------------------
+
+The +destroy+ method of an Active Record model instance removes the corresponding record from the database. After that's done, there isn't any record to display, so Rails redirects the user's browser to the index view for the model.
-==== Edit & Update
+== Adding a Second Model
-For the `edit`, `update`, and `destroy` actions, we will use the same `@post = Post.find(params[:id])` to find the appropriate record.
+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.
+
+=== Generating a Model
+
+Models in Rails use a singular name, and their corresponding database tables use a plural name. For the model to hold comments, the convention is to use the name Comment. Even if you don't want to use the entire apparatus set up by scaffolding, most Rails developers still use generators to make things like models and controllers. To create the new model, run this command in your terminal:
+
+[source, shell]
+-------------------------------------------------------
+$ script/generate model Comment commenter:string body:text post:references
+-------------------------------------------------------
+
+This command will generate four files:
+
+* +app/models/comment.rb+ - The model
+* +db/migrate/20081013214407_create_comments.rb - The migration
+* +test/unit/comment_test.rb+ and +test/fixtures/comments.yml+ - The test harness.
+
+First, take a look at +comment.rb+:
+
+[source, ruby]
+-------------------------------------------------------
+class Comment < ActiveRecord::Base
+ belongs_to :post
+end
+-------------------------------------------------------
-==== Destroy
+This is very similar to the +post.rb+ model that you saw earlier. The difference is the line +belongs_to :post+, which sets up an Active Record _association_. You'll learn a little about associations in the next section of this guide.
-Description of the destroy action
+In addition to the model, Rails has also made a migration to create the corresponding database table:
-=== The View
-The view is where you put all the code that gets seen by the user: divs, tables, text, checkboxes, etc. Think of the view as the home of your HTML. If done correctly, there should be no business logic in the view.
+[source, ruby]
+-------------------------------------------------------
+class CreateComments < ActiveRecord::Migration
+ def self.up
+ create_table :comments do |t|
+ t.string :commenter
+ t.text :body
+ t.references :post
+
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :comments
+ end
+end
+-------------------------------------------------------
+
+The +t.references+ line sets up a foreign key column for the association between the two models. Go ahead and run the migration:
+
+[source, shell]
+-------------------------------------------------------
+$ rake db:migrate
+-------------------------------------------------------
+
+Rails is smart enough to only execute the migrations that have not already been run against this particular database.
+
+=== Associating Models
+
+Active Record associations let you declaratively quantify the relationship between two models. In the case of comments and posts, you could write out the relationships this way:
+
+* Each comment belongs to one post
+* One post can have many comments
+
+In fact, this is very close to the syntax that Rails uses to declare this association. You've already seen the line of code inside the Comment model that makes each comment belong to a Post:
+
+[source, ruby]
+-------------------------------------------------------
+class Comment < ActiveRecord::Base
+ belongs_to :post
+end
+-------------------------------------------------------
+
+You'll need to edit the +post.rb+ file to add the other side of the association:
+
+[source, ruby]
+-------------------------------------------------------
+class Post < ActiveRecord::Base
+ has_many :comments
+end
+-------------------------------------------------------
+
+These two declarations enable a good bit of automatic behavior. For example, if you have an instance variable +@post+ containing a post, you can retrieve all the comments belonging to that post as the array +@post.comments+.
+
+TIP: For more information on Active Record associations, see the link:../activerecord/association_basics.html+[Active Record Associations] guide.
+
+=== Adding a Route
+
+_Routes_ are entries in the +config/routes.rb+ file that tell Rails how to match incoming HTTP requests to controller actions. Open up that file and find the existing line referring to +posts+. Then edit it as follows:
+
+[source, ruby]
+-------------------------------------------------------
+map.resources :posts do |post|
+ post.resources :comments
+end
+-------------------------------------------------------
+
+This creates +comments+ as a _nested resource_ within +posts+. This is another part of capturing the hierarchical relationship that exists between posts and comments.
+
+TIP: For more information on routing, see the link:../routing/routing_outside_in[Rails Routing from the Outside In] guide.
+
+=== Generating a Controller
+
+With the model in hand, you can turn your attention to creating a matching controller. Again, there's a generator for this:
+
+[source, shell]
+-------------------------------------------------------
+$ script/generate controller Comments index show new edit
+-------------------------------------------------------
+
+This creates seven files:
+
+* +app/controllers/comments_controller.rb+ - The controller
+* +app/helpers/comments_helper.rb - A view helper file
+* +app/views/comments/index.html.erb - The view for the index action
+* +app/views/comments/show.html.erb - The view for the show action
+* +app/views/comments/new.html.erb - The view for the new action
+* +app/views/comments/edit.html.erb - The view for the edit action
+* +test/functional/comments_controller_test.rb - The functional tests for the controller
+
+The controller will be generated with empty methods for each action that you specified in the call to +script/generate controller+:
+
+[source, ruby]
+-------------------------------------------------------
+class CommentsController < ApplicationController
+ def index
+ end
+
+ def show
+ end
+
+ def new
+ end
+
+ def edit
+ end
+
+end
+-------------------------------------------------------
+
+You'll need to flesh this out with code to actually process requests appropriately in each method. Here's a version that (for simplicity's sake) only responds to requests that require HTML:
+
+[source, ruby]
+-------------------------------------------------------
+class CommentsController < ApplicationController
+ def index
+ @post = Post.find(params[:post_id])
+ @comments = @post.comments
+ end
+
+ def show
+ @post = Post.find(params[:post_id])
+ @comment = Comment.find(params[:id])
+ end
+
+ def new
+ @post = Post.find(params[:post_id])
+ @comment = @post.comments.build
+ end
+
+ def create
+ @post = Post.find(params[:post_id])
+ @comment = @post.comments.build(params[:comment])
+ if @comment.save
+ redirect_to post_comment_path(@post, @comment)
+ else
+ render :action => "new"
+ end
+ end
+
+ def edit
+ @post = Post.find(params[:post_id])
+ @comment = Comment.find(params[:id])
+ end
+
+ def update
+ @post = Post.find(params[:post_id])
+ @comment = Comment.find(params[:id])
+ if @comment.update_attributes(params[:comment])
+ redirect_to post_comment_path(@post, @comment)
+ else
+ render :action => "edit"
+ end
+ end
+
+end
+-------------------------------------------------------
+
+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.
+
+=== Building Views
+
+Because you skipped scaffolding, you'll need to build views for comments "by hand." Invoking +script/generate controller+ will give you skeleton views, but they'll be devoid of actual content. Here's a first pass at fleshing out the comment views.
+
+The +index.html.erb+ view:
+
+[source, ruby]
+-------------------------------------------------------
+<h1>Comments for <%= @post.title %></h1>
+<table>
+ <tr>
+ <th>Commenter</th>
+ <th>Body</th>
+ </tr>
+
+<% for comment in @comments %>
+ <tr>
+ <td><%=h comment.commenter %></td>
+ <td><%=h comment.body %></td>
+ <td><%= link_to 'Show', post_comment_path(@post, comment) %></td>
+ <td><%= link_to 'Edit', edit_post_comment_path(@post, comment) %></td>
+ <td><%= link_to 'Destroy', post_comment_path(@post, comment), :confirm => 'Are you sure?', :method => :delete %></td>
+ </tr>
+<% end %>
+</table>
+
+<br />
+
+<%= link_to 'New comment', new_post_comment_path(@post) %>
+<%= link_to 'Back to Post', @post %>
+-------------------------------------------------------
+
+The +new.html.erb+ view:
+
+[source, ruby]
+-------------------------------------------------------
+<h1>New comment</h1>
+
+<% form_for([@post, @comment]) do |f| %>
+ <%= f.error_messages %>
+
+ <p>
+ <%= f.label :commenter %><br />
+ <%= f.text_field :commenter %>
+ </p>
+ <p>
+ <%= f.label :body %><br />
+ <%= f.text_area :body %>
+ </p>
+ <p>
+ <%= f.submit "Create" %>
+ </p>
+<% end %>
+
+<%= link_to 'Back', post_comments_path(@post) %>
+-------------------------------------------------------
+
+The +show.html.erb+ view:
+
+[source, ruby]
+-------------------------------------------------------
+<h1>Comment on <%= @post.title %></h1>
+
+<p>
+ <b>Commenter:</b>
+ <%=h @comment.commenter %>
+</p>
+
+<p>
+ <b>Comment:</b>
+ <%=h @comment.body %>
+</p>
+
+<%= link_to 'Edit', edit_post_comment_path(@post, @comment) %> |
+<%= link_to 'Back', post_comments_path(@post) %>
+-------------------------------------------------------
+
+The +edit.html.erb+ view:
+
+[source, ruby]
+-------------------------------------------------------
+<h1>Editing comment</h1>
+
+<% form_for([@post, @comment]) do |f| %>
+ <%= f.error_messages %>
+
+ <p>
+ <%= f.label :commenter %><br />
+ <%= f.text_field :commenter %>
+ </p>
+ <p>
+ <%= f.label :body %><br />
+ <%= f.text_area :body %>
+ </p>
+ <p>
+ <%= f.submit "Update" %>
+ </p>
+<% end %>
+
+<%= link_to 'Show', post_comment_path(@post, @comment) %> |
+<%= link_to 'Back', post_comments_path(@post) %>
+-------------------------------------------------------
+
+Again, the added complexity here (compared to the views you saw for managing comments) comes from the necessity of juggling a post and its comments at the same time.
+
+=== Hooking Comments to Posts
+
+As a final step, I'll modify the +show.html.erb+ view for a post to show the comments on that post, and to allow managing those comments:
+
+[source, ruby]
+-------------------------------------------------------
+<p>
+ <b>Name:</b>
+ <%=h @post.name %>
+</p>
+
+<p>
+ <b>Title:</b>
+ <%=h @post.title %>
+</p>
+
+<p>
+ <b>Content:</b>
+ <%=h @post.content %>
+</p>
+
+<h2>Comments</h2>
+<% @post.comments.each do |c| %>
+ <p>
+ <b>Commenter:</b>
+ <%=h c.commenter %>
+ </p>
+
+ <p>
+ <b>Comment:</b>
+ <%=h c.body %>
+ </p>
+<% end %>
+
+<%= link_to 'Edit', edit_post_path(@post) %> |
+<%= link_to 'Back', posts_path %>
+<%= link_to 'Manage Comments', post_comments_path(@post) %>
+-------------------------------------------------------
+
+Note that each post has its own individual comments collection, accessible as +@post.comments+. That's a consequence of the declarative associations in the models. Path helpers such as +post_comments_path+ come from the nested route declaration in +config/routes.rb+.
+
+== What's Next?
+
+Now that you've seen your first Rails application, you should feel free to update it and experiment on your own. But you don't have to do everything without help. As you need assistance getting up and running with Rails, feel free to consult these support resources:
+
+* The [http://manuals.rubyonrails.org/]Ruby On Rails guides
+* The link:http://groups.google.com/group/rubyonrails-talk[Ruby on Rails mailing list]
+* The #rubyonrails channel on irc.freenode.net
+* The link:http://wiki.rubyonrails.org/rails[Rails wiki]
+
+== Changelog ==
+http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/2[Lighthouse ticket]
+
+* October 16, 2008: Revised based on feedback from Pratik Naik by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
+* October 13, 2008: First complete draft by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
+* October 12, 2008: More detail, rearrangement, editing by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
+* September 8, 2008: initial version by James Miller (not yet approved for publication)
diff --git a/railties/doc/guides/index.txt b/railties/doc/guides/index.txt
index ad82aea3ec..1e6d5665f8 100644
--- a/railties/doc/guides/index.txt
+++ b/railties/doc/guides/index.txt
@@ -43,8 +43,6 @@ This guide covers the find method defined in ActiveRecord::Base, as well as name
.link:actionview/layouts_and_rendering.html[Layouts and Rendering in Rails]
***********************************************************
-CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/15[Lighthouse Ticket]
-
This guide covers the basic layout features of Action Controller and Action View,
including rendering and redirecting, using +content_for_ blocks, and working
with partials.
diff --git a/railties/doc/guides/routing/routing_outside_in.txt b/railties/doc/guides/routing/routing_outside_in.txt
index f35ac0cebd..ff41bc0257 100644
--- a/railties/doc/guides/routing/routing_outside_in.txt
+++ b/railties/doc/guides/routing/routing_outside_in.txt
@@ -267,10 +267,28 @@ Rails allows you to group your controllers into namespaces by saving them in fol
map.resources :adminphotos, :controller => "admin/photos"
-------------------------------------------------------
-If you use controller namespaces, you need to be aware of a subtlety in the Rails routing code: it always tries to preserve as much of the namespace from the previous request as possible. For example, if you are on a view generated from the +adminphoto_path+ helper, and you follow a link generated with +<%= link_to "show", adminphoto(1) %> you will end up on the view generated by +admin/photos/show+ but you will also end up in the same place if you have +<%= link_to "show", {:controller => "photos", :action => "show"} %>+ because Rails will generate the show URL relative to the current URL.
+If you use controller namespaces, you need to be aware of a subtlety in the Rails routing code: it always tries to preserve as much of the namespace from the previous request as possible. For example, if you are on a view generated from the +adminphoto_path+ helper, and you follow a link generated with +<%= link_to "show", adminphoto(1) %>+ you will end up on the view generated by +admin/photos/show+ but you will also end up in the same place if you have +<%= link_to "show", {:controller => "photos", :action => "show"} %>+ because Rails will generate the show URL relative to the current URL.
TIP: If you want to guarantee that a link goes to a top-level controller, use a preceding slash to anchor the controller name: +<%= link_to "show", {:controller => "/photos", :action => "show"} %>+
+You can also specify a controller namespace with the +:namespace+ option instead of a path:
+
+[source, ruby]
+-------------------------------------------------------
+map.resources :adminphotos, :namespace => "admin", :controller => "photos"
+-------------------------------------------------------
+
+This can be especially useful when combined with +with_options+ to map multiple namespaced routes together:
+
+[source, ruby]
+-------------------------------------------------------
+map.with_options(:namespace => "admin") do |admin|
+ admin.resources :photos, :videos
+end
+-------------------------------------------------------
+
+That would give you routing for +admin/photos+ and +admin/videos+ controllers.
+
==== Using :singular
If for some reason Rails isn't doing what you want in converting the plural resource name to a singular name in member routes, you can override its judgment with the +:singular+ option:
@@ -366,6 +384,8 @@ Routes recognized by this entry would include:
NOTE: In most cases, it's simpler to recognize URLs of this sort by creating nested resources, as discussed in the next section.
+NOTE: You can also use +:path_prefix+ with non-RESTful routes.
+
==== Using :name_prefix
You can use the :name_prefix option to avoid collisions between routes. This is most useful when you have two resources with the same name that use +:path_prefix+ to map differently. For example:
@@ -378,6 +398,8 @@ map.resources :photos, :path_prefix => '/agencies/:agency_id', :name_prefix => '
This combination will give you route helpers such as +photographer_photos_path+ and +agency_edit_photo_path+ to use in your code.
+NOTE: You can also use +:name_prefix+ with non-RESTful routes.
+
=== Nested Resources
It's common to have resources that are logically children of other resources. For example, suppose your application includes these models:
@@ -417,7 +439,7 @@ PUT /magazines/1/ads/1 Ads update update a specific ad be
DELETE /magazines/1/ads/1 Ads destroy delete a specific ad belonging to a specific magazine
--------------------------------------------------------------------------------------------
-This will also create routing helpers such as +magazine_ads_url+ and +magazine_edit_ad_path+.
+This will also create routing helpers such as +magazine_ads_url+ and +edit_magazine_ad_path+.
==== Using :name_prefix
diff --git a/railties/doc/guides/securing_rails_applications/security.txt b/railties/doc/guides/securing_rails_applications/security.txt
index f0db7a7ac2..aa1fcf4171 100644
--- a/railties/doc/guides/securing_rails_applications/security.txt
+++ b/railties/doc/guides/securing_rails_applications/security.txt
@@ -79,7 +79,7 @@ This will also be a good idea, if you modify the structure of an object and old
-- _Rails provides several storage mechanisms for the session hashes, the most important are ActiveRecordStore and CookieStore._
-There are a number of session storages, i.e. where Rails saves the session hash and session id. Mot real-live applications choose ActiveRecordStore (or one of its derivatives) over file storage due to performance and maintenance reasons. ActiveRecordStore keeps the session id and hash in a database table and saves and retrieves the hash on every request.
+There are a number of session storages, i.e. where Rails saves the session hash and session id. Most real-live applications choose ActiveRecordStore (or one of its derivatives) over file storage due to performance and maintenance reasons. ActiveRecordStore keeps the session id and hash in a database table and saves and retrieves the hash on every request.
Rails 2 introduced a new default session storage, CookieStore. CookieStore saves the session hash directly in a cookie on the client-side. The server retrieves the session hash from the cookie and eliminates the need for a session id. That will greatly increase the speed of the application, but it is a controversial storage option and you have to think about the security implications of it:
@@ -507,7 +507,7 @@ It is interesting that only 4% of these passwords were dictionary words and the
A good password is a long alphanumeric combination of mixed cases. As this is quite hard to remember, it is advisable to enter only the [,#fffcdb]#first letters of a sentence that you can easily remember#. For example "The quick brown fox jumps over the lazy dog" will be "Tqbfjotld". Note that this is just an example, you should not use well known phrases like these, as they might appear in cracker dictionaries, too.
=== Regular expressions
--- _A common pitfall in Ruby's regular expressions is to match the string's end and beginning by $ and ^, instead of \z and \A._
+-- _A common pitfall in Ruby's regular expressions is to match the string's beginning and end by ^ and $, instead of \A and \z._
Ruby uses a slightly different approach to match the end and the beginning of a string. That is why even many Ruby and Rails books make this wrong. So how is this a security threat? Imagine you have a File model and you validate the file name by a regular expression like this:
@@ -523,7 +523,7 @@ This means, upon saving, the model will validate the file name to consist only o
file.txt%0A<script>alert('hello')</script>
..........
-Whereas %0A is a line feed and %0D is a carriage return, in URL encoding. This file name passes the filter because the regular expression matches – up to the line end, the rest does not matter. The correct expression should read:
+Whereas %0A is a line feed in URL encoding, so Rails automatically converts it to "file.txt\n<script>alert('hello')</script>". This file name passes the filter because the regular expression matches – up to the line end, the rest does not matter. The correct expression should read:
..........
/\A[\w\.\-\+]+\z/
@@ -859,4 +859,4 @@ The security landscape shifts and it is important to keep up to date, because mi
- Subscribe to the Rails security http://groups.google.com/group/rubyonrails-security[mailing list]
- http://secunia.com/[Keep up to date on the other application layers] (they have a weekly newsletter, too)
- A http://ha.ckers.org/blog/[good security blog] including the http://ha.ckers.org/xss.html[Cross-Site scripting Cheat Sheet]
-- Another http://www.0x000000.com/[good security blog] with some Cheat Sheets, too \ No newline at end of file
+- Another http://www.0x000000.com/[good security blog] with some Cheat Sheets, too
diff --git a/railties/doc/guides/testing_rails_applications/testing_rails_applications.txt b/railties/doc/guides/testing_rails_applications/testing_rails_applications.txt
index 11ff2e6a41..dc7635eff9 100644
--- a/railties/doc/guides/testing_rails_applications/testing_rails_applications.txt
+++ b/railties/doc/guides/testing_rails_applications/testing_rails_applications.txt
@@ -3,55 +3,42 @@ A Guide to Testing Rails Applications
This guide covers built-in mechanisms offered by Rails to test your application. By referring to this guide, you will be able to:
-* Understand Rails testing terminologies
+* Understand Rails testing terminology
* Write unit, functional and integration tests for your application
-* Read about other popular testing approaches and plugins
+* Identify other popular testing approaches and plugins
-Assumptions:
+This guide won't teach you to write a Rails application; it assumes basic familiarity with the Rails way of doing things.
- * You have spent more than 15 minutes in building your first application
- * The guide has been written for Rails 2.1 and above
+== Why Write Tests for your Rails Applications? ==
-== Why write tests for your Rails applications? ==
-
- * Since Ruby code that you write in your Rails application is interpreted, you may only find that its broken when you actually run your application server and use it through the browser. Writing tests is a clean way of running through your code and catching syntactical and logic errors.
- * Rails tests can also simulate browser requests and thus you can test your applications response without having to test it through your browser.
+ * Because Ruby code that you write in your Rails application is interpreted, you may only find that it's broken when you actually run your application server and use it through the browser. Writing tests is a clean way of running through your code in advance and catching syntactical and logic errors.
+ * Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.
* By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring.
- * Rails makes it super easy to write your tests. Its starts producing skeleton code in background while you are creating your models and controllers.
+ * Rails makes it super easy to write your tests. It starts by producing skeleton test code in background while you are creating your models and controllers.
-== Before you start writing tests ==
+== Before you Start Writing Tests ==
-=== The 3 Environments ===
+Just about every Rails application interacts heavily with a database - and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.
-Testing support was woven into the Rails fabric from the beginning. It wasn't a ``oh! let's bolt on support for running tests because they're new and cool'' epiphany.
+=== The 3 Environments ===
-Each Rails application you build has 3 sides. A side for production, a side for development and a side for testing.
+Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. One of the consequences of this design decision is that every Rails application you build has 3 sides: a side for production, a side for development, and a side for testing.
-Let's take a closer look at the Rails 'config/database.yml' file. This YAML configuration file has 3 different sections defining 3 unique database setups:
+One place you'll find this distinction is in the +config/database.yml+ file. This YAML configuration file has 3 different sections defining 3 unique database setups:
* production
* development
* test
-===== Why 3 different databases? =====
-
-Well, there's one for testing where you can use sample data, there's one for development where you'll be most of the time as you develop your application, and then production for the ``real deal'', or when it goes live.
-
-Every new Rails application should have these 3 sections filled out. They should point to different databases. You may end up not having a local database for your production environment, but development and test should both exist and be different.
-
-===== Why Make This Distinction? =====
-
-If you stop and think about it for a second, it makes sense.
+This allows you to set up and interact with test data without any danger of your tests altering data from your production environment.
-By segregating your development database and your testing database, you're not in any danger of losing any data where it matters.
+For example, suppose you need to test your new +delete_this_user_and_every_everything_associated_with_it+ function. Wouldn't you want to run this in an environment where it makes no difference if you destroy data or not?
-For example, you need to test your new `delete_this_user_and_every_everything_associated_with_it` function. Wouldn't you want to run this in an environment which makes no difference if you destroy data or not?
+When you do end up destroying your testing database (and it will happen, trust me), you can rebuild it from scratch according to the specs defined in the development database. You can do this by running +rake db:test:prepare+.
-When you do end up destroying your testing database (and it will happen, trust me), simply run a task in your rakefile to rebuild it from scratch according to the specs defined in the development database. You can do this by running `rake db:test:prepare`.
+=== Rails Sets up for Testing from the Word Go ===
-=== Rails kicks-in right from the word go ===
-
-Rails creates a test folder for you as soon as you initiate a Rails project using `rails application_name`. If you list the contents of this folder then you shall see:
+Rails creates a +test+ folder for you as soon as you create a Rails project using +rails _application_name_+. If you list the contents of this folder then you shall see:
[source,shell]
------------------------------------------------------
@@ -60,22 +47,25 @@ $ ls -F test/
fixtures/ functional/ integration/ test_helper.rb unit/
------------------------------------------------------
-The 'unit' folder is meant to hold tests for your models, 'functional' folder is meant to hold tests for your controllers and 'integration' folder is meant to hold tests that involves any number of controllers. Fixtures are a way of organizing data that you want to test against and reside in the 'fixtures' folder. 'test_helper.rb' holds default configuration for your tests.
+The +unit+ folder is meant to hold tests for your models, the +functional+ folder is meant to hold tests for your controllers, and the +integration+ folder is meant to hold tests that involve any number of controllers interacting. Fixtures are a way of organizing test data; they reside in the +fixtures+ folder. The +test_helper.rb+ file holds the default configuration for your tests.
+
+=== The Low-Down on Fixtures ===
-=== The Lo-Down on Fixtures ===
+For good tests, you'll need to give some thought to setting up test data. In Rails, you can handle this by defining and customizing fixtures.
-==== What They Are ====
+==== What Are Fixtures? ====
-Fixtures is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: *YAML* or *CSV*.
+_Fixtures_ is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: *YAML* or *CSV*.
-You'll find fixtures under your 'test/fixtures' directory. When you run `script/generate model` to create a new model, fixture stubs will be automatically created and placed in this directory.
+You'll find fixtures under your +test/fixtures+ directory. When you run +script/generate model+ to create a new model, fixture stubs will be automatically created and placed in this directory.
==== YAML the Camel is a Mammal with Enamel ====
-YAML-formatted fixtures are a very human-friendly way to describe your sample data. These types of fixtures have the *.yml* file extension (as in 'users.yml').
+YAML-formatted fixtures are a very human-friendly way to describe your sample data. These types of fixtures have the *.yml* file extension (as in +users.yml+).
-On any given day, a YAML fixture file may look like this:
+Here's a sample YAML fixture file:
+[source,ruby]
---------------------------------------------
# low & behold! I am a YAML comment!
david:
@@ -91,14 +81,15 @@ steve:
profession: guy with keyboard
---------------------------------------------
-Each fixture is given a 'name' followed by an indented list of colon-separated key/value pairs. Records are separated by a blank space. You can place comments by using the # character in the first column.
+Each fixture is given a name followed by an indented list of colon-separated key/value pairs. Records are separated by a blank space. You can place comments in a fixture file by using the # character in the first column.
==== Comma Seperated ====
-Fixtures can also be described using the all-too-familiar comma-separated value file format. These files, just like YAML fixtures are placed in the 'test/fixtures' directory, but these end with the *.csv* file extension (as in 'celebrity_holiday_figures.csv').
+Fixtures can also be described using the all-too-familiar comma-separated value (CSV) file format. These files, just like YAML fixtures, are placed in the 'test/fixtures' directory, but these end with the +.csv+ file extension (as in +celebrity_holiday_figures.csv+).
A CSV fixture looks like this:
+[source, log]
--------------------------------------------------------------
id, username, password, stretchable, comments
1, sclaus, ihatekids, false, I like to say ""Ho! Ho! Ho!""
@@ -108,28 +99,27 @@ id, username, password, stretchable, comments
The first line is the header. It is a comma-separated list of fields. The rest of the file is the payload: 1 record per line. A few notes about this format:
- * each cell is stripped of outward facing spaces
- * if you use a comma as data, the cell must be encased in quotes
- * if you use a quote as data, you must escape it with a 2nd quote
- * don't use blank lines
- * nulls can be achived by just placing a comma, for example, (1,sclaus,,false,) minus the parenthesis of course.
+ * Leading and trailing spaces are trimmed from each value when it is imported
+ * If you use a comma as data, the cell must be encased in quotes
+ * If you use a quote as data, you must escape it with a 2nd quote
+ * Don't use blank lines
+ * Nulls can be defined by including no data between a pair of commas
-Unlike the YAML format where you give each fixture a name, CSV fixture names are automatically generated. They follow a pattern of ``model-name-counter''. In the above example, you would have:
+Unlike the YAML format where you give each record in a fixture a name, CSV fixture names are automatically generated. They follow a pattern of "model-name-counter". In the above example, you would have:
---------------------------------------------------------------
-celebrity-holiday-figures-1
-celebrity-holiday-figures-2
-celebrity-holiday-figures-3
---------------------------------------------------------------
+* +celebrity-holiday-figures-1+
+* +celebrity-holiday-figures-2+
+* +celebrity-holiday-figures-3+
The CSV format is great to use if you have existing data in a spreadsheet or database and you are able to save it (or export it) as a CSV.
==== ERb'in It Up ====
-ERb allows you embed ruby code within templates. Both the YAML and CSV fixture formats are pre-processed with ERb. This allows you to use Ruby to help you generate some sample data.
+ERb allows you embed ruby code within templates. Both the YAML and CSV fixture formats are pre-processed with ERb when you load fixtures. This allows you to use Ruby to help you generate some sample data.
I'll demonstrate with a YAML file:
+[source, ruby]
--------------------------------------------------------------
<% earth_size = 20 -%>
mercury:
@@ -147,38 +137,32 @@ mars:
Anything encased within the
--------------
-<% -%>
--------------
-
-tag is considered Ruby code. To actually print something out, you must use the
-
--------------
-<%= %>
--------------
+[source, ruby]
+------------------------
+<% %>
+------------------------
-tag.
+tag is considered Ruby code. When this fixture is loaded, the +size+ attribute of the three records will be set to 20/50, 20/2, and 20-69 respectively.
==== Fixtures in Action ====
-Rails by default automatically loads all fixtures from the 'test/fixtures' folder for your unit and functional test. Along with which it does 3 things. Let's see an example for 'users' fixture file:
- * it nukes any existing data living in the users table
- * it loads the fixture data (if any) into the users table
- * it dumps the data into a variable in case you want to access it directly
+Rails by default automatically loads all fixtures from the 'test/fixtures' folder for your unit and functional test. Loading involves three steps:
+
+ * Remove any existing data from the table corresponding to the fixture
+ * Load the fixture data into the table
+ * Dump the fixture data into a variable in case you want to access it directly
==== Hashes with Special Powers ====
-Fixtures are basically Hash objects. As mentioned in point #3 above, you can access the hash object directly because it is automatically setup as a local variable of the test case.
+Fixtures are basically Hash objects. As mentioned in point #3 above, you can access the hash object directly because it is automatically setup as a local variable of the test case. For example:
[source, ruby]
--------------------------------------------------------------
-...
- # this will return the Hash for the fixture named david
- users(:david)
+# this will return the Hash for the fixture named david
+users(:david)
- # this will return the property for david called id
- users(:david).id
-...
+# this will return the property for david called id
+users(:david).id
--------------------------------------------------------------
But, by there's another side to fixtures... at night, if the moon is full and the wind completely still, fixtures can also transform themselves into the form of the original class!
@@ -187,35 +171,33 @@ Now you can get at the methods only available to that class.
[source, ruby]
--------------------------------------------------------------
-...
- # using the find method, we grab the "real" david as a User
- david = users(:david).find
+# using the find method, we grab the "real" david as a User
+david = users(:david).find
- # an now we have access to methods only available to a User class
- email( david.girlfriend.email, david.illegitimate_children )
-...
+# and now we have access to methods only available to a User class
+email(david.girlfriend.email, david.location_tonight)
--------------------------------------------------------------
-== Unit tests for your Models ==
+== Unit Testing Your Models ==
In Rails, unit tests are what you write to test your models.
-When you create a model using `script/generate`, among other things it creates a test stub in the 'test/unit' folder.
+When you create a model using +script/generate+, among other things it creates a test stub in the +test/unit+ folder, as well as a fixture for the model:
+[source, log]
-------------------------------------------------------
$ script/generate model Post
...
- create app/models/post.rb
- create test/unit/post_test.rb
- create test/fixtures/posts.yml
+create app/models/post.rb
+create test/unit/post_test.rb
+create test/fixtures/posts.yml
...
-------------------------------------------------------
-The default test stub in 'test/unit/post_test.rb' should look like:
+The default test stub in +test/unit/post_test.rb+ looks like this:
[source,ruby]
--------------------------------------------------
-
require 'test_helper'
class PostTest < ActiveSupport::TestCase
@@ -226,30 +208,48 @@ class PostTest < ActiveSupport::TestCase
end
--------------------------------------------------
-Let's examine this file line by line so that you have a clear understanding of the involved terminologies.
+A line by line examination of this file will help get you oriented to Rails testing code and terminology.
-`require 'test_helper'`
+[source,ruby]
+--------------------------------------------------
+require 'test_helper'
+--------------------------------------------------
+
+As you know by now that `test_helper.rb` specifies the default configuration to run our tests. This is included with all the tests, so any methods added to this file are available to all your tests.
-As you know by now that `test_helper.rb` specifies the default configuration to run our tests. This is included with all the tests. Thus any methods added to this file are available to all your tests.
+[source,ruby]
+--------------------------------------------------
+class PostTest < ActiveSupport::TestCase
+--------------------------------------------------
-`class PostTest < ActiveSupport::TestCase`
+The +PostTest+ class defines a _test case_ because it inherits from +ActiveSupport::TestCase+. +PostTest+ thus has all the methods available from +ActiveSupport::TestCase+. You'll see those methods a little later in this guide.
-Class 'PostTest' is called a test case as it inherits from `ActiveSupport::TestCase`. 'PostTest' thus has all the methods available for ActiveSupport::TestCase. We shall look into the methods available a little later in this guide.
+[source,ruby]
+--------------------------------------------------
+def test_truth
+--------------------------------------------------
-`def test_truth`
+Any method defined within a test case that begins with +test+ (case sensitive) is simply called a test. So, +test_password+, +test_valid_password+ and +testValidPassword+ all are legal test names and are run automatically when the test case is run.
-Any method defined within a Test Case that begins with 'test' (case sensitive) is simply called a test. So, test_password, test_valid_password and testValidPassword all are legal test names and are run automatically when the test case is run.
+[source,ruby]
+--------------------------------------------------
+assert true
+--------------------------------------------------
-`assert true`
+This line of code is called an _assertion_. An assertion is a line of code that evaluates an object (or expression) for expected results. For example, an assertion can check:
-This line of code is called an assertion. An Assertion is 1 line of code that evaluates an object (or expression) for expected results. For example, is this value = that value? is this object nil? does this line of code throw an exception? is the user's password greater than 5 characters? The assert method is available as 'PostTest' inherits from `ActiveSupport::TestCase`
+* is this value = that value?
+* is this object nil?
+* does this line of code throw an exception?
+* is the user's password greater than 5 characters?
-A test consists of one or more assertions. Only when all the assertions are successful the test passes.
+Every test contains one or more assertions. Only when all the assertions are successful the test passes.
-=== Running your test ===
+=== Running Tests ===
-Running a test is as simple as invoking the file through Ruby.
+Running a test is as simple as invoking the file containing the test cases through Ruby:
+[source, shell]
-------------------------------------------------------
$ cd test
$ ruby unit/post_test.rb
@@ -262,10 +262,11 @@ Finished in 0.023513 seconds.
1 tests, 1 assertions, 0 failures, 0 errors
-------------------------------------------------------
-This would run all the test methods from the test case.
+This will run all the test methods from the test case.
-You could also run a particular test method from the test case by using the `-n` switch with the 'test method name'
+You can also run a particular test method from the test case by using the +-n+ switch with the +test method name+.
+[source, log]
-------------------------------------------------------
$ ruby unit/post_test.rb -n test_truth
@@ -277,25 +278,21 @@ Finished in 0.023513 seconds.
1 tests, 1 assertions, 0 failures, 0 errors
-------------------------------------------------------
-The '.' (dot) above indicates a passing test. When a test fails you see a F or if there is an error you see an E in its place. The last line of the output is the summary.
+The +.+ (dot) above indicates a passing test. When a test fails you see an +F+; when a test throws an error you see an +E+ in its place. The last line of the output is the summary.
-To see how a test failure is reported, lets write a test which reports a failure.
+To see how a test failure is reported, you can add a failing test to the +post_test.rb+ test case:
[source,ruby]
--------------------------------------------------
-# test/unit/post_test.rb
-...
- def test_should_have_atleast_one_post
- post = Post.find(:first)
- assert_not_nil post
- end
-...
+def test_should_have_atleast_one_post
+ post = Post.find(:first)
+ assert_not_nil post
+end
--------------------------------------------------
-Here I am assuming you have still not added fixture data in posts.yml
-
-Let's run this test.
+If you haven't added any data to the test fixture for posts, this test will fail. You can see this by running it:
+[source, log]
-------------------------------------------------------
$ ruby unit/post_test.rb
Loaded suite unit/post_test
@@ -313,21 +310,19 @@ test_should_have_atleast_one_post(PostTest)
2 tests, 2 assertions, 1 failures, 0 errors
-------------------------------------------------------
-Above, 'F' denotes a failure and its corresponding trace is shown under '1)' along with the name of the test failing, which is: test_should_have_atleast_one_post(PostTest). The next few lines contain the stack trace followed by a message which mentions the actual value and the expected value by the assertion. Though, it is not highly readable it does provide us with just enough information at most times. To make the assertion failure message more readable every assertion provides an optional message parameter. Let's see the same assertion with a message parameter.
+In the output, +F+ denotes a failure. You can see the corresponding trace shown under +1)+ along with the name of the failing test. The next few lines contain the stack trace followed by a message which mentions the actual value and the expected value by the assertion. The default assertion messages provide just enough information to help pinpoint the error. To make the assertion failure message more readable every assertion provides an optional message parameter, as shown here:
[source,ruby]
--------------------------------------------------
-# test/unit/post_test.rb
-...
- def test_should_have_atleast_one_post
- post = Post.find(:first)
- assert_not_nil post, "Should not be nil as Posts table should have atleast one post"
- end
-...
+def test_should_have_atleast_one_post
+ post = Post.find(:first)
+ assert_not_nil post, "Should not be nil as Posts table should have atleast one post"
+end
--------------------------------------------------
-Let's run this test in the console.
+Running this test shows the friendlier assertion message:
+[source, log]
-------------------------------------------------------
$ ruby unit/post_test.rb
Loaded suite unit/post_test
@@ -346,24 +341,20 @@ Should not be nil as Posts table should have atleast one post.
2 tests, 2 assertions, 1 failures, 0 errors
-------------------------------------------------------
-Now you can see an additional message in the test failure report which makes much more sense while troubleshooting.
-
-To see how an error is reported, let's add a test to our test case that introduces an error.
+To see how an error gets reported, here's a test containing an error:
[source,ruby]
--------------------------------------------------
-# test/unit/post_test.rb
-...
- def test_should_report_error
- # some_undefined_variable is not defined elsewhere in the test case
- some_undefined_variable
- assert true
- end
-...
+def test_should_report_error
+ # some_undefined_variable is not defined elsewhere in the test case
+ some_undefined_variable
+ assert true
+end
--------------------------------------------------
-Let's run this test in our console.
+Now you can see even more output in the console from running the tests:
+[source, log]
-------------------------------------------------------
$ ruby unit/post_test.rb
Loaded suite unit/post_test
@@ -392,128 +383,86 @@ NameError: undefined local variable or method `some_undefined_variable' for #<Po
Notice the 'E' in the output. It denotes a test with error.
-A thing to note here is that the execution of the test method is stopped as soon as an error or a assertion failure is encountered and the test suite continues with the next method. All test methods are executed in alphabetical order.
-
-=== What to include in your Unit Tests ===
-
-Ideally you would like to include a test for everything which could probably break. Its a good practice to have a test for each of your validations and at least 1 test for every method in your model.
-
-=== Assertions Available ===
-
-By now you've caught a glimpse of some of the assertions that are available. Assertions are the worker bees of testing. They are the ones that actually perform the checks to ensure things are going as planned.
-
-There are a bunch of different types of assertions you can use. Here's the complete list of assertions that ship with test/unit. The [msg] is an optional string message you can specify to make your test failure messages clearer. It's not required.
-
-`assert( boolean, [msg] )`::
-Ensures that the object/expression is true.
-
-`assert_equal( obj1, obj2, [msg] )`::
-Ensures that `obj1 == obj2` is true.
-
-`assert_not_equal( obj1, obj2, [msg] )`::
-Ensures that `obj1 == obj2` is false.
-
-`assert_same( obj1, obj2, [msg] )`::
-Ensures that `obj1.equal?(obj2)` is true.
-
-`assert_not_same( obj1, obj2, [msg] )`::
-Ensures that `obj1.equal?(obj2)` is false.
-
-`assert_nil( obj, [msg] )`::
-Ensures that `obj.nil?` is true.
-
-`assert_not_nil( obj, [msg] )`::
-Ensures that `obj.nil?` is false.
-
-`assert_match( regexp, string, [msg] )`::
-Ensures that a string matches the regular expression.
-
-`assert_no_match( regexp, string, [msg] )`::
-Ensures that a string doesn't matches the regular expression.
-
-`assert_in_delta( expecting, actual, delta, [msg] )`::
-Ensures that the numbers `expecting` and `actual` are within `delta` of each other.
-
-`assert_throws( symbol, [msg] ) { block }`::
-Ensures that the given block throws the symbol.
-
-`assert_raises( exception1, exception2, ... ) { block }`::
-Ensures that the given block raises one of the given exceptions.
-
-`assert_nothing_raised( exception1, exception2, ... ) { block }`::
-Ensures that the given block doesn't raise one of the given exceptions.
-
-`assert_instance_of( class, obj, [msg] )`::
-Ensures that `obj` is of the `class` type.
-
-`assert_kind_of( class, obj, [msg] )`::
-Ensures that `obj` is or descends from `class`.
+NOTE: The execution of each test method stops as soon as any error or a assertion failure is encountered, and the test suite continues with the next method. All test methods are executed in alphabetical order.
-`assert_respond_to( obj, symbol, [msg] )`::
-Ensures that obj has a method called symbol.
+=== What to Include in Your Unit Tests ===
-`assert_operator( obj1, operator, obj2, [msg] )`::
-Ensures that `obj1.operator(obj2)` is true.
+Ideally you would like to include a test for everything which could possibly break. It's a good practice to have at least one test for each of your validations and at least one test for every method in your model.
-`assert_send( array, [msg] )`::
-Ensures that executing the method listed in `array[1]` on the object in `array[0]` with the parameters of `array[2 and up]` is true. This one is weird eh?
+TIP: Many Rails developers practice _test-driven development_ (TDD), in which the tests are written _before_ the code that they are testing. This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with link:http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html[15 TDD steps to create a Rails application].
-`flunk( [msg] )`::
-Ensures failure... like me and high school chemistry exams.
+=== Assertions Available ===
-Because of the modular nature of the testing framework, it is possible to create your own assertions. In fact, that's exactly what Rails does. It has some specialized assertions to make your life easier.
+By now you've caught a glimpse of some of the assertions that are available. Assertions are the worker bees of testing. They are the ones that actually perform the checks to ensure that things are going as planned.
-Creating your own assertions is more of an advanced topic we won't cover in this tutorial.
+There are a bunch of different types of assertions you can use. Here's the complete list of assertions that ship with +test/unit+, the testing library used by Rails. The +[msg]+ parameter is an optional string message you can specify to make your test failure messages clearer. It's not required.
+[grid="all"]
+`-----------------------------------------------------------------`------------------------------------------------------------------------
+Assertion Purpose
+------------------------------------------------------------------------------------------------------------------------------------------
++assert( boolean, [msg] )+ Ensures that the object/expression is true.
++assert_equal( obj1, obj2, [msg] )+ Ensures that +obj1 == obj2+ is true.
++assert_not_equal( obj1, obj2, [msg] )+ Ensures that +obj1 == obj2+ is false.
++assert_same( obj1, obj2, [msg] )+ Ensures that +obj1.equal?(obj2)+ is true.
++assert_not_same( obj1, obj2, [msg] )+ Ensures that +obj1.equal?(obj2)+ is false.
++assert_nil( obj, [msg] )+ Ensures that +obj.nil?+ is true.
++assert_not_nil( obj, [msg] )+ Ensures that +obj.nil?+ is false.
++assert_match( regexp, string, [msg] )+ Ensures that a string matches the regular expression.
++assert_no_match( regexp, string, [msg] )+ Ensures that a string doesn't matches the regular expression.
++assert_in_delta( expecting, actual, delta, [msg] )+ Ensures that the numbers `expecting` and `actual` are within `delta` of each other.
++assert_throws( symbol, [msg] ) { block }+ Ensures that the given block throws the symbol.
++assert_raises( exception1, exception2, ... ) { block }+ Ensures that the given block raises one of the given exceptions.
++assert_nothing_raised( exception1, exception2, ... ) { block }+ Ensures that the given block doesn't raise one of the given exceptions.
++assert_instance_of( class, obj, [msg] )+ Ensures that +obj+ is of the +class+ type.
++assert_kind_of( class, obj, [msg] )+ Ensures that +obj+ is or descends from +class+.
++assert_respond_to( obj, symbol, [msg] )+ Ensures that +obj+ has a method called +symbol+.
++assert_operator( obj1, operator, obj2, [msg] )+ Ensures that +obj1.operator(obj2)+ is true.
++assert_send( array, [msg] )+ Ensures that executing the method listed in +array[1]+ on the object in +array[0]+ with the parameters of +array[2 and up]+ is true. This one is weird eh?
++flunk( [msg] )+ Ensures failure. This is useful to explicitly mark a test that isn't finished yet.
+------------------------------------------------------------------------------------------------------------------------------------------
+
+Because of the modular nature of the testing framework, it is possible to create your own assertions. In fact, that's exactly what Rails does. It includes some specialized assertions to make your life easier.
+
+NOTE: Creating your own assertions is an advanced topic that we won't cover in this tutorial.
=== Rails Specific Assertions ===
-`assert_valid(record)`::
-Ensures that the passed record is valid by Active Record standards and returns any error messages if it is not.
-
-`assert_difference(expressions, difference = 1, message = nil) {|| ...}`::
-Test numeric difference between the return value of an expression as a result of what is evaluated in the yielded block.
-
-`assert_no_difference(expressions, message = nil, &block)`::
-Assertion that the numeric result of evaluating an expression is not changed before and after invoking the passed in block.
-
-`assert_recognizes(expected_options, path, extras={}, message=nil)`::
-Asserts that the routing of the given path was handled correctly and that the parsed options (given in the expected_options hash) match path. Basically, it asserts that Rails recognizes the route given by expected_options.
-
-`assert_generates(expected_path, options, defaults={}, extras = {}, message=nil)`::
-Asserts that the provided options can be used to generate the provided path. This is the inverse of assert_recognizes. The extras parameter is used to tell the request the names and values of additional request parameters that would be in a query string. The message parameter allows you to specify a custom error message for assertion failures.
+Rails adds some custom assertions of its own to the +test/unit+ framework:
-`assert_response(type, message = nil)`::
-Asserts that the response is one of the following types:
- * :success - Status code was 200
- * :redirect - Status code was in the 300-399 range
- * :missing - Status code was 404
- * :error - Status code was in the 500-599 range
-
-`assert_redirected_to(options = {}, message=nil)`::
-Assert that the redirection options passed in match those of the redirect called in the latest action. This match can be partial, such that assert_redirected_to(:controller => "weblog") will also match the redirection of redirect_to(:controller => "weblog", :action => "show") and so on.
-
-`assert_template(expected = nil, message=nil)`::
-Asserts that the request was rendered with the appropriate template file.
+[grid="all"]
+`----------------------------------------------------------------------------------`-------------------------------------------------------
+Assertion Purpose
+------------------------------------------------------------------------------------------------------------------------------------------
++assert_valid(record)+ Ensures that the passed record is valid by Active Record standards and returns any error messages if it is not.
++assert_difference(expressions, difference = 1, message = nil) {|| ...}+ Test numeric difference between the return value of an expression as a result of what is evaluated in the yielded block.
++assert_no_difference(expressions, message = nil, &block)+ Asserts that the numeric result of evaluating an expression is not changed before and after invoking the passed in block.
++assert_recognizes(expected_options, path, extras={}, message=nil)+ Asserts that the routing of the given path was handled correctly and that the parsed options (given in the expected_options hash) match path. Basically, it asserts that Rails recognizes the route given by expected_options.
++assert_generates(expected_path, options, defaults={}, extras = {}, message=nil)+ Asserts that the provided options can be used to generate the provided path. This is the inverse of assert_recognizes. The extras parameter is used to tell the request the names and values of additional request parameters that would be in a query string. The message parameter allows you to specify a custom error message for assertion failures.
++assert_response(type, message = nil)+ Asserts that the response comes with a specific status code. You can specify +:success+ to indicate 200, +:redirect+ to indicate 300-399, +:missing+ to indicate 404, or +:error+ to match the 500-599 range
++assert_redirected_to(options = {}, message=nil)+ Assert that the redirection options passed in match those of the redirect called in the latest action. This match can be partial, such that +assert_redirected_to(:controller => "weblog")+ will also match the redirection of +redirect_to(:controller => "weblog", :action => "show")+ and so on.
++assert_template(expected = nil, message=nil)+ Asserts that the request was rendered with the appropriate template file.
+------------------------------------------------------------------------------------------------------------------------------------------
-You would get to see the usage of some of these assertions in the next chapter.
+You'll see the usage of some of these assertions in the next chapter.
-== Functional tests for your Controllers ==
+== Functional Tests for Your Controllers ==
-In Rails, testing various actions of a single controller is termed as writing functional tests for that controller. Controllers handle the incoming web requests to your application and eventually respond with a rendered view.
+In Rails, testing the various actions of a single controller is called writing functional tests for that controller. Controllers handle the incoming web requests to your application and eventually respond with a rendered view.
=== What to include in your Functional Tests ===
You should test for things such as:
* was the web request successful?
- * were we redirected to the right page?
- * were we successfully authenticated?
+ * was the user redirected to the right page?
+ * was the user successfully authenticated?
* was the correct object stored in the response template?
* was the appropriate message displayed to the user in the view
-When you use `script/generate` to create a controller, it automatically creates a functional test for that controller in 'test/functional'. Let's create a post controller:
+When you use +script/generate+ to create a controller, it automatically creates a functional test for that controller in +test/functional+. For example, if you create a post controller:
+[source, shell]
-------------------------------------------------------
$ script/generate controller post
...
@@ -522,7 +471,7 @@ $ script/generate controller post
...
-------------------------------------------------------
-Now if you take a look at the file 'posts_controller_test.rb' in the 'test/functional' directory, you should see:
+Now if you take a look at the file +posts_controller_test.rb+ in the +test/functional+ directory, you should see:
[source,ruby]
--------------------------------------------------
@@ -536,106 +485,107 @@ class PostsControllerTest < ActionController::TestCase
end
--------------------------------------------------
-
-Example functional tests for posts controller:
+Of course, you need to replace the simple assertion with real testing. Here's a starting example of a functional test:
[source,ruby]
--------------------------------------------------
- def test_should_get_index
- get :index
- assert_response :success
- assert_not_nil assigns(:posts)
- end
+def test_should_get_index
+ get :index
+ assert_response :success
+ assert_not_nil assigns(:posts)
+end
--------------------------------------------------
+In the +test_should_get_index+ test, Rails simulates a request on the action called index, making sure the request was successful and also ensuring that it assigns a valid +posts+ instance variable.
-In the test_should_get_index test, we are simulating a request on the action called index, making sure the request was successful and also ensuring that it assigns a valid `posts` instance variable.
+The +get+ method kicks off the web request and populates the results into the response. It accepts 4 arguments:
-The get method kicks off the web request and populates the results into the response. It accepts 4 arguments.
+* The action of the controller you are requesting. This can be in the form of a string or a symbol.
+* An optional hash of request parameters to pass into the action (eg. query string parameters or post variables).
+* An optional hash of session variables to pass along with the request.
+* An optional hash of flash values.
- * The action of the controller you are requesting. It can be in the form of a string or a symbol.
- * An optional hash of request parameters to pass into the action (eg. query string parameters or post variables).
- * An optional hash of session variables to pass along with the request.
- * An optional hash of flash to stash your goulash.
-
-Example: Calling the :show action, passing an id of 12 as the params and setting user_id of 5 in the session.
+Example: Calling the +:show+ action, passing an +id+ of 12 as the +params+ and setting a +user_id+ of 5 in the session:
+[source,ruby]
+--------------------------------------------------
get(:show, {'id' => "12"}, {'user_id' => 5})
+--------------------------------------------------
-Another example: Calling the :view action, passing an id of 12 as the params, this time with no session, but with a flash message.
+Another example: Calling the +:view+ action, passing an +id+ of 12 as the +params+, this time with no session, but with a flash message.
+[source,ruby]
+--------------------------------------------------
get(:view, {'id' => '12'}, nil, {'message' => 'booya!'})
+--------------------------------------------------
-=== Available request types at your disposal ===
+=== Available Request Types for Functional Tests===
-For those of you familiar with HTTP protocol, you'll know that get is a type of request. There are 5 request types supported in Rails:
+If you're familiar with the HTTP protocol, you'll know that +get+ is a type of request. There are 5 request types supported in Rails functional tests:
- * get
- * post
- * put
- * head
- * delete
+* +get+
+* +post+
+* +put+
+* +head+
+* +delete+
All of request types are methods that you can use, however, you'll probably end up using the first two more often than the others.
-=== The 4 Hashes of the Apocolypse ===
-
-After the request has been made by using one of the 5 methods (get, post, etc…), you will have 4 Hash objects ready for use.
-
-They are (starring in alphabetical order):
+=== The 4 Hashes of the Apocalypse ===
-`assigns`::
-Any objects that are stored as instance variables in actions for use in views.
+After a request has been made by using one of the 5 methods (+get+, +post+, etc.) and processed, you will have 4 Hash objects ready for use:
-`cookies`::
-Any objects cookies that are set.
+* +assigns+ - Any objects that are stored as instance variables in actions for use in views.
+* +cookies+ - Any cookies that are set.
+* +flash+ - Any objects living in the flash.
+* +session+ - Any object living in session variables.
-`flash`::
-Any objects living in the flash.
-
-`session`::
-Any object living in session variables.
-
-As is the case with normal Hash objects, you can access the values by referencing the keys by string. You can also reference them by symbol name… except assigns. Check it out:
+As is the case with normal Hash objects, you can access the values by referencing the keys by string. You can also reference them by symbol name, except for +assigns+. For example:
+[source,ruby]
+--------------------------------------------------
flash["gordon"] flash[:gordon]
session["shmession"] session[:shmession]
cookies["are_good_for_u"] cookies[:are_good_for_u]
# Because you can't use assigns[:something] for historical reasons:
assigns["something"] assigns(:something)
+--------------------------------------------------
+
+=== Instance Variables Available ===
+
+You also have access to three instance variables in your functional tests:
-=== Instance variables available ===
+* +@controller+ - The controller processing the request
+* +@request+ - The request
+* +@response+ - The response
- * `@controller`
- * `@request`
- * `@response`
+=== A Fuller Functional Test Example
-Another example that uses flash, assert_redirected_to, assert_difference
+Here's another example that uses +flash+, +assert_redirected_to+, and +assert_difference+:
[source,ruby]
--------------------------------------------------
- def test_should_create_post
- assert_difference('Post.count') do
- post :create, :post => { :title => 'Hi', :body => 'This is my first post.'}
- end
- assert_redirected_to post_path(assigns(:post))
- assert_equal 'Post was successfully created.', flash[:notice]
+def test_should_create_post
+ assert_difference('Post.count') do
+ post :create, :post => { :title => 'Hi', :body => 'This is my first post.'}
end
+ assert_redirected_to post_path(assigns(:post))
+ assert_equal 'Post was successfully created.', flash[:notice]
+end
--------------------------------------------------
=== Testing Views ===
-Testing the response to your request by asserting the presence of key html elements and their content is a good practice. `assert_select` allows you to do all this by using a simple yet powerful syntax.
+Testing the response to your request by asserting the presence of key HTML elements and their content is a useful way to test the views of your application. The +assert_select+ assertion allows you to do this by using a simple yet powerful syntax.
+
+NOTE: You may find references to +assert_tag+ in other documentation, but this is now deprecated in favor of +assert_select+.
-[NOTE]
-`assert_tag` is now deprecated in favor of `assert_select`
+There are two forms of +assert_select+:
-`assert_select(selector, [equality], [message])`::
-Ensures that the equality condition is met on the selected elements through the selector. The selector may be a CSS selector expression (String), an expression with substitution values, or an HTML::Selector object.
++assert_select(selector, [equality], [message])`+ ensures that the equality condition is met on the selected elements through the selector. The selector may be a CSS selector expression (String), an expression with substitution values, or an +HTML::Selector+ object.
-`assert_select(element, selector, [equality], [message])`::
-Ensures that the equality condition is met on all the selected elements through the selector starting from the _element_ (instance of HTML::Node) and its descendants.
++assert_select(element, selector, [equality], [message])+ ensures that the equality condition is met on all the selected elements through the selector starting from the _element_ (instance of +HTML::Node+) and its descendants.
For example, you could verify the contents on the title element in your response with:
@@ -644,7 +594,7 @@ For example, you could verify the contents on the title element in your response
assert_select 'title', "Welcome to Rails Testing Guide"
--------------------------------------------------
-You can also use nested `assert_select` blocks. In this case the inner `assert_select` will run the assertion on each element selected by the outer `assert_select` block.
+You can also use nested +assert_select+ blocks. In this case the inner +assert_select+ will run the assertion on each element selected by the outer `assert_select` block:
[source,ruby]
--------------------------------------------------
@@ -653,12 +603,23 @@ assert_select 'ul.navigation' do
end
--------------------------------------------------
-`assert_select` is really powerful and I would recommend you to go through its http://api.rubyonrails.com/classes/ActionController/Assertions/SelectorAssertions.html#M000749[documentation] for its advanced usage.
+The +assert_select+ assertion is quite powerful. For more advanced usage, refer to its link:http://api.rubyonrails.com/classes/ActionController/Assertions/SelectorAssertions.html#M000749[documentation].
-==== Additional view based assertions ====
+==== Additional View-based Assertions ====
-`assert_select_email`::
-Allows you to make assertions on the body of an e-mail.
+There are more assertions that are primarily used in testing views:
+
+[grid="all"]
+`----------------------------------------------------------------------------------`-------------------------------------------------------
+Assertion Purpose
+------------------------------------------------------------------------------------------------------------------------------------------
++assert_select_email+ Allows you to make assertions on the body of an e-mail.
++assert_select_rjs+ Allows you to make assertions on RJS response. +assert_select_rjs+ has variants which allow you to narrow down on the updated element or even a particular operation on an element.
++assert_select_encoded+ Allows you to make assertions on encoded HTML. It does this by un-encoding the contents of each element and then calling the block with all the un-encoded elements.
++css_select(selector)+ or +css_select(element, selector)+ Returns an array of all the elements selected by the _selector_. In the second variant it first matches the base _element_ and tries to match the _selector_ expression on any of its children. If there are no matches both variants return an empty array.
+------------------------------------------------------------------------------------------------------------------------------------------
+
+Here's an example of using +assert_select_email+:
[source,ruby]
--------------------------------------------------
@@ -667,35 +628,26 @@ assert_select_email do
end
--------------------------------------------------
-`assert_select_rjs`::
-Allows you to make assertions on RJS response. `assert_select_rjs` has variants which allow you to narrow down upon the updated element or event a particular operation on an element.
-
-`assert_select_encoded`::
-Allows you to make assertions on encoded HTML. It does this by un-encoding the contents of each element and then calling the block with all the un-encoded elements.
-
-`css_select(selector)`::
-`css_select(element, selector)`::
-Returns an array of all the elements selected by the _selector_. In the second variant it first matches the base _element_ and tries to match the _selector_ expression on any of its children. If there are no matches both variants return an empty array.
-
== Integration Testing ==
-Integration tests are used to test interaction among any number of controllers. They are generally used to test important work flows within your application.
+Integration tests are used to test the interaction among any number of controllers. They are generally used to test important work flows within your application.
-Unlike Unit and Functional tests they have to be explicitly created under the 'test/integration' folder within our application. Rails provides a generator to create an integration test skeleton for you.
-
-Example:
+Unlike Unit and Functional tests, integration tests have to be explicitly created under the 'test/integration' folder within your application. Rails provides a generator to create an integration test skeleton for you.
+[source, shell]
--------------------------------------------------
-$ script/generate integration_test create_blog_and_then_post_comments
+$ script/generate integration_test user_flows
exists test/integration/
- create test/integration/create_blog_and_then_post_comments_test.rb
+ create test/integration/user_flows_test.rb
--------------------------------------------------
+Here's what a freshly-generated integration test looks like:
+
[source,ruby]
--------------------------------------------------
require 'test_helper'
-class CreateBlogAndThenPostCommentsTest < ActionController::IntegrationTest
+class UserFlowsTest < ActionController::IntegrationTest
# fixtures :your, :models
# Replace this with your real tests.
@@ -705,234 +657,238 @@ class CreateBlogAndThenPostCommentsTest < ActionController::IntegrationTest
end
--------------------------------------------------
-=== Differences in comparison to unit and functional tests ===
-
-* You will have to include fixtures explicitly unlike unit and functional tests in which all the fixtures are loaded by default (through test_helper)
-* Additional helpers: https?, https!, host!, follow_redirect!, post/get_via_redirect, open_session, reset
+Integration tests inherit from +ActionController::IntegrationTest+. This makes available some additional helpers to use in your integration tests. Also you need to explicitly include the fixtures to be made available to the test.
-== Rake Tasks for Testing
+=== Helpers Available for Integration tests ===
-The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project.
+In addition to the standard testing helpers, there are some additional helpers available to integration tests:
-.Default Rake tasks
[grid="all"]
--------------------------
-Tasks Description
--------------------------
-`rake test` Runs all unit, functional and integration tests. You can also simply run `rake` as _test_ target is default.
-`rake test:units` Runs all the unit tests from 'test/unit'
-`rake test:functionals` Runs all the functional tests from 'test/functional'
-`rake test:integration` Runs all the integration tests from 'test/integration'
-`rake test:recent` Tests recent changes
-`rake test:uncommitted` Runs all the tests which are uncommitted. Only supports Subversion
-`rake test:plugins` Run all the plugin tests from vendor/plugins/*/**/test (or specify with `PLUGIN=_name_`)
-`rake db:test:clone` Recreate the test database from the current environment's database schema
-`rake db:test:clone_structure` Recreate the test databases from the development structure
-`rake db:test:load` Recreate the test database from the current schema.rb
-`rake db:test:prepare` Check for pending migrations and load the test schema
-`rake db:test:purge` Empty the test database.
--------------------------
-
-TIP: You can see all these rake task and their descriptions by running `rake --tasks --describe`
+`----------------------------------------------------------------------------------`-------------------------------------------------------
+Helper Purpose
+------------------------------------------------------------------------------------------------------------------------------------------
++https?+ Returns +true+ if the session is mimicking a secure HTTPS request.
++https!+ Allows you to mimic a secure HTTPS request.
++host!+ Allows you to set the host name to use in the next request.
++redirect?+ Returns +true+ if the last request was a redirect.
++follow_redirect!+ Follows a single redirect response.
++request_via_redirect(http_method, path, [parameters], [headers])+ Allows you to make an HTTP request and follow any subsequent redirects.
++post_via_redirect(path, [parameters], [headers])+ Allows you to make an HTTP POST request and follow any subsequent redirects.
++get_via_redirect(path, [parameters], [headers])+ Allows you to make an HTTP GET request and follow any subsequent redirects.
++put_via_redirect(path, [parameters], [headers])+ Allows you to make an HTTP PUT request and follow any subsequent redirects.
++delete_via_redirect(path, [parameters], [headers])+ Allows you to make an HTTP DELETE request and follow any subsequent redirects.
++open_session+ Opens a new session instance.
+------------------------------------------------------------------------------------------------------------------------------------------
+
+=== Integration Testing Examples ===
+
+A simple integration test that exercises multiple controllers:
-== Testing Your Mailers ==
+[source,ruby]
+--------------------------------------------------
+require 'test_helper'
-=== Keeping the postman in check ===
+class UserFlowsTest < ActionController::IntegrationTest
+ fixtures :users
-Your ActionMailer -- like every other part of your Rails application -- should be tested to ensure that it is working as expected.
+ def test_login_and_browse_site
+ # login via https
+ https!
+ get "/login"
+ assert_response :success
+
+ post_via_redirect "/login", :username => users(:avs).username, :password => users(:avs).password
+ assert_equal '/welcome', path
+ assert_equal 'Welcome avs!', flash[:notice]
+
+ https!(false)
+ get "/posts/all"
+ assert_response :success
+ assert assigns(:products)
+ end
+end
+--------------------------------------------------
-The goal of testing your ActionMailer is to ensure that:
+As you can see the integration test involves multiple controllers and exercises the entire stack from database to dispatcher. In addition you can have multiple session instances open simultaneously in a test and extend those instances with assertion methods to create a very powerful testing DSL (domain-specific language) just for your application.
- * emails are being processed (created and sent)
- * the email content is correct (subject, sender, body, etc)
- * the right emails are being sent at the righ times
+Here's an example of multiple sessions and custom DSL in an integration test
-==== From all sides ====
+[source,ruby]
+--------------------------------------------------
+require 'test_helper'
-There are two aspects of testing your mailer, the unit tests and the functional tests.
-Unit tests
+class UserFlowsTest < ActionController::IntegrationTest
+ fixtures :users
-In the unit tests, we run the mailer in isolation with tightly controlled inputs and compare the output to a known-value -- a fixture -- yay! more fixtures!
+ def test_login_and_browse_site
+
+ # User avs logs in
+ avs = login(:avs)
+ # User guest logs in
+ guest = login(:guest)
+
+ # Both are now available in different sessions
+ assert_equal 'Welcome avs!', avs.flash[:notice]
+ assert_equal 'Welcome guest!', guest.flash[:notice]
+
+ # User avs can browse site
+ avs.browses_site
+ # User guest can browse site aswell
+ guest.browses_site
+
+ # Continue with other assertions
+ end
+
+ private
+
+ module CustomDsl
+ def browses_site
+ get "/products/all"
+ assert_response :success
+ assert assigns(:products)
+ end
+ end
+
+ def login(user)
+ open_session do |sess|
+ sess.extend(CustomDsl)
+ u = users(user)
+ sess.https!
+ sess.post "/login", :username => u.username, :password => u.password
+ assert_equal '/welcome', path
+ sess.https!(false)
+ end
+ end
+end
+--------------------------------------------------
-==== Functional tests ====
+== Testing Your Mailers ==
-In the functional tests we don't so much test the minute details produced by the mailer, instead we test that our controllers and models are using the mailer in the right way. We test to prove that the right email was sent at the right time.
+Testing mailer classes requires some specific tools to do a thorough job.
-=== Unit Testing ===
+=== Keeping the Postman in Check ===
-In order to test that your mailer is working as expected, we can use unit tests to compare the actual results of the mailer with pre-writen examples of what should be produced.
+Your +ActionMailer+ classes -- like every other part of your Rails application -- should be tested to ensure that it is working as expected.
-==== Revenge of the fixtures ====
+The goals of testing your +ActionMailer+ classes are to ensure that:
-For the purposes of unit testing a mailer, fixtures are used to provide an example of how output ``should'' look. Because these are example emails, and not Active Record data like the other fixtures, they are kept in their own subdirectory from the other fixtures. Don't tease them about it though, they hate that.
+* emails are being processed (created and sent)
+* the email content is correct (subject, sender, body, etc)
+* the right emails are being sent at the right times
-When you generated your mailer (you did that right?) the generator created stub fixtures for each of the mailers actions. If you didn't use the generator you'll have to make those files yourself.
+==== From All Sides ====
-==== The basic test case ====
+There are two aspects of testing your mailer, the unit tests and the functional tests. In the unit tests, you run the mailer in isolation with tightly controlled inputs and compare the output to a knownvalue (a fixture -- yay! more fixtures!). In the functional tests you don't so much test the minute details produced by the mailer Instead we test that our controllers and models are using the mailer in the right way. You test to prove that the right email was sent at the right time.
-Here is an example of what you start with.
+=== Unit Testing ===
-[source, ruby]
--------------------------------------------------
-require File.dirname(__FILE__) + '/. ./test_helper'
+In order to test that your mailer is working as expected, you can use unit tests to compare the actual results of the mailer with pre-written examples of what should be produced.
-class MyMailerTest < Test::Unit::TestCase
- FIXTURES_PATH = File.dirname(__FILE__) + '/. ./fixtures'
+==== Revenge of the Fixtures ====
- def setup
- ActionMailer::Base.delivery_method = :test
- ActionMailer::Base.perform_deliveries = true
- ActionMailer::Base.deliveries = []
+For the purposes of unit testing a mailer, fixtures are used to provide an example of how the output _should_ look. Because these are example emails, and not Active Record data like the other fixtures, they are kept in their own subdirectory apart from the other fixtures. The name of the directory within +test/fixtures+ directly corresponds to the name of the mailer. So, for a mailer named +UserMailer+, the fixtures should reside in +test/fixtures/user_mailer+ directory.
- @expected = TMail::Mail.new
- end
+When you generated your mailer, the generator creates stub fixtures for each of the mailers actions. If you didn't use the generator you'll have to make those files yourself.
- def test_signup
- @expected.subject = 'MyMailer#signup'
- @expected.body = read_fixture('signup')
- @expected.date = Time.now
+==== The Basic Test case ====
- assert_equal @expected.encoded, MyMailer.create_signup(@expected.date).encoded
- end
-
- private
- def read_fixture(action)
- IO.readlines("#{FIXTURES_PATH}/my_mailer/#{action}")
- end
-end
--------------------------------------------------
-
-The `setup` method is mostly concerned with setting up a blank slate for the next test. However it is worth describing what each statement does
+Here's a unit test to test a mailer named +UserMailer+ whose action +invite+ is used to send an invitation to a friend. It is an adapted version of the base test created by the generator for an +invite+ action.
[source, ruby]
-------------------------------------------------
-ActionMailer::Base.delivery_method = :test
--------------------------------------------------
-
-sets the delivery method to test mode so that email will not actually be delivered (useful to avoid spamming your users while testing) but instead it will be appended to an array (ActionMailer::Base.deliveries).
+require 'test_helper'
-[source, ruby]
--------------------------------------------------
-ActionMailer::Base.perform_deliveries = true
--------------------------------------------------
+class UserMailerTest < ActionMailer::TestCase
+ tests UserMailer
+ def test_invite
+ @expected.from = 'me@example.com'
+ @expected.to = 'friend@example.com'
+ @expected.subject = "You have been invited by #{@expected.from}"
+ @expected.body = read_fixture('invite')
+ @expected.date = Time.now
-Ensures the mail will be sent using the method specified by ActionMailer::Base.delivery_method, and finally
+ assert_equal @expected.encoded, UserMailer.create_invite('me@example.com', 'friend@example.com', @expected.date).encoded
+ end
-[source, ruby]
--------------------------------------------------
-ActionMailer::Base.deliveries = []
+end
-------------------------------------------------
-sets the array of sent messages to an empty array so we can be sure that anything we find there was sent as part of our current test.
+In this test, +@expected+ is an instance of +TMail::Mail+ that you can use in your tests. It is defined in +ActionMailer::TestCase+. The test above uses +@expected+ to construct an email, which it then asserts with email created by the custom mailer. The +invite+ fixture is the body of the email and is used as the sample content to assert against. The helper +read_fixture+ is used to read in the content from this file.
-However often in unit tests, mails will not actually be sent, simply constructed, as in the example above, where the precise content of the email is checked against what it should be. Dave Thomas suggests an alternative approach, which is just to check the part of the email that is likely to break, i.e. the dynamic content. The following example assumes we have some kind of user table, and we might want to mail those users new passwords:
+Here's the content of the +invite+ fixture:
-[source, ruby]
+[source, log]
-------------------------------------------------
-require File.dirname(__FILE__) + '/../test_helper'
-require 'my_mailer'
-
-class MyMailerTest < Test::Unit::TestCase
- fixtures :users
- FIXTURES_PATH = File.dirname(__FILE__) + '/../fixtures'
- CHARSET = "utf-8"
-
- include ActionMailer::Quoting
-
- def setup
- ActionMailer::Base.delivery_method = :test
- ActionMailer::Base.perform_deliveries = true
- ActionMailer::Base.deliveries = []
-
- @expected = TMail::Mail.new
- @expected.set_content_type "text", "plain", { "charset" => CHARSET }
- end
-
- def test_reset_password
- user = User.find(:first)
- newpass = 'newpass'
- response = MyMailer.create_reset_password(user,newpass)
- assert_equal 'Your New Password', response.subject
- assert_match /Dear #{user.full_name},/, response.body
- assert_match /New Password: #{newpass}/, response.body
- assert_equal user.email, response.to[0]
- end
+Hi friend@example.com,
- private
- def read_fixture(action)
- IO.readlines("#{FIXTURES_PATH}/community_mailer/#{action}")
- end
+You have been invited.
- def encode(subject)
- quoted_printable(subject, CHARSET)
- end
-end
+Cheers!
-------------------------------------------------
-and here we check the dynamic parts of the mail, specifically that we use the users' correct full name and that we give them the correct password.
+This is the right time to understand a little more about writing tests for your mailers. The line +ActionMailer::Base.delivery_method = :test+ in +config/environments/test.rb+ sets the delivery method to test mode so that email will not actually be delivered (useful to avoid spamming your users while testing) but instead it will be appended to an array (+ActionMailer::Base.deliveries+).
+
+However often in unit tests, mails will not actually be sent, simply constructed, as in the example above, where the precise content of the email is checked against what it should be.
=== Functional Testing ===
-Functional testing involves more than just checking that the email body, recipients and so forth are correct. In functional mail tests we call the mail deliver methods and check that the appropriate emails have been appended to the delivery list. It is fairly safe to assume that the deliver methods themselves do their job -- what we are probably more interested in is whether our own business logic is sending emails when we expect them to. For example the password reset operation we used an example in the previous section will probably be called in response to a user requesting a password reset through some sort of controller.
+Functional testing for mailers involves more than just checking that the email body, recipients and so forth are correct. In functional mail tests you call the mail deliver methods and check that the appropriate emails have been appended to the delivery list. It is fairly safe to assume that the deliver methods themselves do their job You are probably more interested in is whether your own business logic is sending emails when you expect them to got out. For example, you can check that the invite friend operation is sending an email appropriately:
[source, ruby]
----------------------------------------------------------------
-require File.dirname(__FILE__) + '/../test_helper'
-require 'my_controller'
+require 'test_helper'
-# Raise errors beyond the default web-based presentation
-class MyController; def rescue_action(e) raise e end; end
+class UserControllerTest < ActionController::TestCase
+ def test_invite_friend
+ assert_difference 'ActionMailer::Base.deliveries.size', +1 do
+ post :invite_friend, :email => 'friend@example.com'
+ end
+ invite_email = ActionMailer::Base.deliveries.first
+
+ assert_equal invite_email.subject, "You have been invited by me@example.com"
+ assert_equal invite_email.to[0], 'friend@example.com'
+ assert_match /Hi friend@example.com/, invite_email.body
+ end
+end
+----------------------------------------------------------------
-class MyControllerTest < Test::Unit::TestCase
+== Rake Tasks for Testing
- def setup
- @controller = MyController.new
- @request, @response = ActionController::TestRequest.new, ActionController::TestResponse.new
- end
+You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of rake tasks to help in testing. The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project.
- def test_reset_password
- num_deliveries = ActionMailer::Base.deliveries.size
- post :reset_password, :email => 'bob@test.com'
+[grid="all"]
+--------------------------------`----------------------------------------------------
+Tasks Description
+------------------------------------------------------------------------------------
++rake test+ Runs all unit, functional and integration tests. You can also simply run +rake+ as the _test_ target is the default.
++rake test:units+ Runs all the unit tests from +test/unit+
++rake test:functionals+ Runs all the functional tests from +test/functional+
++rake test:integration+ Runs all the integration tests from +test/integration+
++rake test:recent+ Tests recent changes
++rake test:uncommitted+ Runs all the tests which are uncommitted. Only supports Subversion
++rake test:plugins+ Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+)
++rake db:test:clone+ Recreate the test database from the current environment's database schema
++rake db:test:clone_structure+ Recreate the test databases from the development structure
++rake db:test:load+ Recreate the test database from the current +schema.rb+
++rake db:test:prepare+ Check for pending migrations and load the test schema
++rake db:test:purge+ Empty the test database.
+------------------------------------------------------------------------------------
- assert_equal num_deliveries+1, ActionMailer::Base.deliveries.size
- end
+TIP: You can see all these rake task and their descriptions by running +rake --tasks --describe+
-end
-----------------------------------------------------------------
+== Other Testing Approaches
-=== Filtering emails in development ===
+The built-in +test/unit+ based testing is not the only way to test Rails applications. Rails developers have come up with a wide variety of other approaches and aids for testing, including:
-Sometimes you want to be somewhere inbetween the `:test` and `:smtp` settings. Say you're working on your development site, and you have a few testers working with you. The site isn't in production yet, but you'd like the testers to be able to receive emails from the site, but no one else. Here's a handy way to handle that situation, add this to your 'environment.rb' or 'development.rb' file
+* link:http://avdi.org/projects/nulldb/[NullDB], a way to speed up testing by avoiding database use.
+* link:http://github.com/thoughtbot/factory_girl/tree/master[Factory Girl], as replacement for fixtures.
+* link:http://www.thoughtbot.com/projects/shoulda[Shoulda], an extension to +test/unit+ with additional helpers, macros, and assertions.
+* link: http://rspec.info/[RSpec], a behavior-driven development framework
-[source, ruby]
-----------------------------------------------------------------
-class ActionMailer::Base
-
- def perform_delivery_fixed_email(mail)
- destinations = mail.destinations
- if destinations.nil?
- destinations = ["mymail@me.com"]
- mail.subject = '[TEST-FAILURE]:'+mail.subject
- else
- mail.subject = '[TEST]:'+mail.subject
- end
- approved = ["testerone@me.com","testertwo@me.com"]
- destinations = destinations.collect{|x| approved.collect{|y| (x==y ? x : nil)}}.flatten.compact
- mail.to = destinations
- if destinations.size > 0
- mail.ready_to_send
- Net::SMTP.start(server_settings[:address], server_settings[:port], server_settings[:domain],
- server_settings[:user_name], server_settings[:password], server_settings[:authentication]) do |smtp|
- smtp.sendmail(mail.encoded, mail.from, destinations)
- end
- end
+== Changelog ==
- end
+http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/8[Lighthouse ticket]
-end
-----------------------------------------------------------------
+* October 14, 2008: Edit and formatting pass by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
+* October 12, 2008: First draft by link:../authors.html#asurve[Akashay Surve] (not yet approved for publication)
-== Guide TODO ==
- * Describe _setup_ and _teardown_
- * Examples for integration test
- * Updating the section on testing mailers