aboutsummaryrefslogtreecommitdiffstats
path: root/railties/doc
diff options
context:
space:
mode:
authorRyan Bigg <radarlistener@gmail.com>2008-10-01 21:38:16 +0930
committerRyan Bigg <radarlistener@gmail.com>2008-10-01 21:38:16 +0930
commitdbbd757edd896947e33fdf18ba870b8df5974d62 (patch)
treecc0428bee430a18200925acb830f3dc3946e31de /railties/doc
parent6aca4458e3a1712a4a675ee7bf2cd35701ff75c9 (diff)
parent8292c7dfce4b893588860053e50ef60ae9a0609a (diff)
downloadrails-dbbd757edd896947e33fdf18ba870b8df5974d62.tar.gz
rails-dbbd757edd896947e33fdf18ba870b8df5974d62.tar.bz2
rails-dbbd757edd896947e33fdf18ba870b8df5974d62.zip
Merge branch 'master' of git@github.com:lifo/docrails
Diffstat (limited to 'railties/doc')
-rw-r--r--railties/doc/guides/.DS_Storebin6148 -> 0 bytes
-rw-r--r--railties/doc/guides/actioncontroller/actioncontroller.txt28
-rw-r--r--railties/doc/guides/actioncontroller/cookies.txt26
-rw-r--r--railties/doc/guides/actioncontroller/filters.txt118
-rw-r--r--railties/doc/guides/actioncontroller/http_auth.txt24
-rw-r--r--railties/doc/guides/actioncontroller/introduction.txt7
-rw-r--r--railties/doc/guides/actioncontroller/methods.txt37
-rw-r--r--railties/doc/guides/actioncontroller/parameter_filtering.txt14
-rw-r--r--railties/doc/guides/actioncontroller/params.txt62
-rw-r--r--railties/doc/guides/actioncontroller/request_response_objects.txt35
-rw-r--r--railties/doc/guides/actioncontroller/rescue.txt3
-rw-r--r--railties/doc/guides/actioncontroller/session.txt130
-rw-r--r--railties/doc/guides/actioncontroller/streaming.txt91
-rw-r--r--railties/doc/guides/actioncontroller/verification.txt3
-rw-r--r--railties/doc/guides/actionview/layouts_and_rendering.txt597
-rw-r--r--railties/doc/guides/activerecord/association_basics.txt393
-rw-r--r--railties/doc/guides/activerecord/images/has_many_through.pngbin112630 -> 100220 bytes
-rw-r--r--railties/doc/guides/activerecord/images/polymorphic.pngbin0 -> 85248 bytes
-rw-r--r--railties/doc/guides/benchmarking_and_profiling/examples/.DS_Storebin6148 -> 0 bytes
-rw-r--r--railties/doc/guides/benchmarking_and_profiling/rubyprof.txt2
-rw-r--r--railties/doc/guides/debugging/debugging_rails_applications.txt2
-rw-r--r--railties/doc/guides/index.txt98
-rw-r--r--railties/doc/guides/migrations/migrations.txt2
-rw-r--r--railties/doc/guides/routing/routing_outside_in.txt16
-rw-r--r--railties/doc/guides/testing_rails_applications/testing_rails_applications.txt137
25 files changed, 1587 insertions, 238 deletions
diff --git a/railties/doc/guides/.DS_Store b/railties/doc/guides/.DS_Store
deleted file mode 100644
index aa78fbf68c..0000000000
--- a/railties/doc/guides/.DS_Store
+++ /dev/null
Binary files differ
diff --git a/railties/doc/guides/actioncontroller/actioncontroller.txt b/railties/doc/guides/actioncontroller/actioncontroller.txt
new file mode 100644
index 0000000000..c5a594d713
--- /dev/null
+++ b/railties/doc/guides/actioncontroller/actioncontroller.txt
@@ -0,0 +1,28 @@
+Action Controller basics
+=======================
+
+In this guide you will learn how controllers work and how they fit into the request cycle in your application. You will learn how to make use of the many tools provided by Action Controller to work with the session, cookies and filters and how to use the built-in HTTP authentication and data streaming facilities. In the end, we will take a look at some tools that will be useful once your controllers are ready and working, like how to filter sensitive parameters from the log and how to rescue and deal with exceptions that may be raised during the request.
+
+include::introduction.txt[]
+
+include::methods.txt[]
+
+include::params.txt[]
+
+include::session.txt[]
+
+include::cookies.txt[]
+
+include::filters.txt[]
+
+include::request_response_objects.txt[]
+
+include::http_auth.txt[]
+
+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
new file mode 100644
index 0000000000..a845e452b2
--- /dev/null
+++ b/railties/doc/guides/actioncontroller/cookies.txt
@@ -0,0 +1,26 @@
+== Cookies ==
+
+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
+
+ def display_foo
+ @foo = cookies[:foo]
+ end
+
+ def remove_foo
+ cookies.delete(:foo)
+ end
+
+end
+-----------------------------------------
+
+Note that while for session values, you set the key to `nil`, to delete a cookie value, you use `cookies.delete(:key)`.
diff --git a/railties/doc/guides/actioncontroller/filters.txt b/railties/doc/guides/actioncontroller/filters.txt
new file mode 100644
index 0000000000..2baf92d6ef
--- /dev/null
+++ b/railties/doc/guides/actioncontroller/filters.txt
@@ -0,0 +1,118 @@
+== Filters ==
+
+Filters are methods that are run before, after or "around" a controller action. For example, one filter might check to see if the logged in user has the right credentials to access that particular controller or action. Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application. A common, simple filter is one which requires that a user is logged in for an action to be run. Let's define the filter method first:
+
+[source, ruby]
+---------------------------------
+class ApplicationController < ActionController::Base
+
+private
+
+ def require_login
+ unless logged_in?
+ flash[:error] = "You must be logged in to access this section"
+ redirect_to new_login_url # Prevents the current action from running
+ end
+ end
+
+ # The logged_in? method simply returns true if the user is logged in and
+ # false otherwise. It does this by "booleanizing" the current_user method
+ # we created previously using a double ! operator. Note that this is not
+ # common in Ruby and is discouraged unless you really mean to convert something
+ # into true or false.
+ def logged_in?
+ !!current_user
+ end
+
+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:
+
+[source, ruby]
+---------------------------------
+class ApplicationController < ActionController::Base
+
+ before_filter :require_login
+
+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 :
+
+[source, ruby]
+---------------------------------
+class LoginsController < Application
+
+ skip_before_filter :require_login, :only => [:new, :create]
+
+end
+---------------------------------
+
+Now, the LoginsController's "new" and "create" actions will work as before without requiring the user to be logged in. The `:only` option is used to only skip this filter for these actions, and there is also an `:except` option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.
+
+=== After filters and around filters ===
+
+In addition to the before filters, you can run filters after an action has run or both before and after. The after filter is similar to the before filter, but because the action has already been run it has access to the response data that's about to be sent to the client. Obviously, after filters can not stop the action from running. Around filters are responsible for running the action, but they can choose not to, which is the around filter's way of stopping it.
+
+TODO: Find a real example for an around filter
+
+[source, ruby]
+---------------------------------
+class ApplicationController < Application
+
+ around_filter :foo
+
+private
+
+ def foo
+ logger.debug("Action has not been run yet")
+ yield #Run the action
+ logger.debug("Action has been run")
+ end
+
+end
+---------------------------------
+
+=== Other types of 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.
+
+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:
+
+[source, ruby]
+---------------------------------
+class ApplicationController < ActionController::Base
+
+ before_filter { |controller| redirect_to new_login_url unless controller.send(:logged_in?) }
+
+end
+---------------------------------
+
+Note that the filter in this case uses `send` because the `logged_in?` method is private and the filter is not run in the scope of the controller. This is not the recommended way to implement this particular filter, but in more simple cases it might be useful.
+
+The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex than can not be implemented in a readable and reusable way using the two other methods. As an example, we will rewrite the login filter again to use a class:
+
+[source, ruby]
+---------------------------------
+class ApplicationController < ActionController::Base
+
+ before_filter LoginFilter
+
+end
+
+class LoginFilter
+
+ def self.filter(controller)
+ unless logged_in?
+ controller.flash[:error] = "You must be logged in to access this section"
+ controller.redirect_to controller.new_login_url
+ end
+ end
+
+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
diff --git a/railties/doc/guides/actioncontroller/http_auth.txt b/railties/doc/guides/actioncontroller/http_auth.txt
new file mode 100644
index 0000000000..5a95de0bb3
--- /dev/null
+++ b/railties/doc/guides/actioncontroller/http_auth.txt
@@ -0,0 +1,24 @@
+== 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
+
+[source, ruby]
+-------------------------------------
+class AdminController < ApplicationController
+
+ USERNAME, PASSWORD = "humbaba", "f59a4805511bf4bb61978445a5380c6c"
+
+ before_filter :authenticate
+
+private
+
+ def authenticate
+ authenticate_or_request_with_http_basic do |username, password|
+ username == USERNAME && Digest::MD5.hexdigest(password) == PASSWORD
+ end
+ end
+
+end
+-------------------------------------
+
+With this in place, you can create namespaced controllers that inherit from AdminController. The before filter will thus be run for all actions in those controllers, protecting them with HTTP Basic authentication.
diff --git a/railties/doc/guides/actioncontroller/introduction.txt b/railties/doc/guides/actioncontroller/introduction.txt
new file mode 100644
index 0000000000..35540bbc09
--- /dev/null
+++ b/railties/doc/guides/actioncontroller/introduction.txt
@@ -0,0 +1,7 @@
+== What does a controller do? ==
+
+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.
+
+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
new file mode 100644
index 0000000000..0818dbb849
--- /dev/null
+++ b/railties/doc/guides/actioncontroller/methods.txt
@@ -0,0 +1,37 @@
+== 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.
+
+[source, ruby]
+----------------------------------------------
+class ClientsController < ActionController::Base
+
+ # Actions are public methods
+ def new
+ end
+
+ # These methods are responsible for producing output
+ def edit
+ end
+
+# Helper methods are private and can not be used as actions
+private
+
+ def foo
+ end
+
+end
+----------------------------------------------
+
+Private methods in a controller are also used as filters, which will be covered later in this guide.
+
+As an example, if the user goes to `/clients/new` in your application to add a new client, a ClientsController instance will be created and the `new` method will be run. Note that the empty method from the example above could work just fine because Rails will by default render the `new.html.erb` view unless the action says otherwise. The `new` method could make available to the view a `@client` instance variable by creating a new Client:
+
+[source, ruby]
+----------------------------------------------
+def new
+ @client = Client.new
+end
+----------------------------------------------
+
+The Layouts & rendering guide explains this in more detail.
diff --git a/railties/doc/guides/actioncontroller/parameter_filtering.txt b/railties/doc/guides/actioncontroller/parameter_filtering.txt
new file mode 100644
index 0000000000..dce4b252c3
--- /dev/null
+++ b/railties/doc/guides/actioncontroller/parameter_filtering.txt
@@ -0,0 +1,14 @@
+== 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":
+
+[source, ruby]
+-------------------------
+class ApplicationController < ActionController::Base
+
+ filter_parameter_logging :password
+
+end
+-------------------------
+
+The method works recursively through all levels of the params hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in return and replaces those for which the block returns true.
diff --git a/railties/doc/guides/actioncontroller/params.txt b/railties/doc/guides/actioncontroller/params.txt
new file mode 100644
index 0000000000..67f97b6135
--- /dev/null
+++ b/railties/doc/guides/actioncontroller/params.txt
@@ -0,0 +1,62 @@
+== Parameters ==
+
+You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, query string parameters. The query string is everything after "?" in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from a HTML form which has been filled in by the user. It's called POST data because it can only be sent as part of an HTTP POST request. Rails does not make any distinction between query string parameters and POST parameters, and both are available in the `params` hash in your controller:
+
+[source, ruby]
+-------------------------------------
+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
+ def index
+ if params[:status] = "activated"
+ @clients = Client.activated
+ else
+ @clients = Client.unativated
+ end
+ end
+
+ # This action uses POST parameters. They are most likely coming from an HTML
+ # form which the user has submitted. The URL for this RESTful request will
+ # be "/clients", and the data will be sent as part of the request body.
+ def create
+ @client = Client.new(params[:client])
+ if @client.save
+ redirect_to @client
+ else
+ # This line overrides the default rendering behavior, which would have been
+ # to render the "create" view.
+ render :action => "new"
+ end
+ end
+
+end
+-------------------------------------
+
+=== Hash and array parameters ===
+
+The params hash is not limited to one-dimensional keys and values. It can contain arrays and (nested) hashes. To send an array of values, append "[]" to the key name:
+
+-------------------------------------
+GET /clients?ids[]=1&ids[2]&ids[]=3
+-------------------------------------
+
+The value of `params[:ids]` will now be `["1", "2", "3"]`. Note that parameter values are always strings; Rails makes no attempt to guess or cast the type.
+
+To send a hash you include the key name inside the brackets:
+
+-------------------------------------
+<form action="/clients">
+ <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" />
+ <input type="text" name="client[address][city]" value="Carrot City" />
+</form>
+-------------------------------------
+
+The value of `params[:client]` when this form is submitted will be `{:name => "Acme", :phone => "12345", :address => {:postcode => "12345", :city => "Carrot City"}}`. Note the nested hash in `params[:client][:address]`.
+
+=== Routing parameters ===
+
+The `params` hash will always contain the `:controller` and `:action` keys, but you should use the methods `controller_name` and `action_name` instead to access these values. Any other parameters defined by the routing, such as `:id` will also be available.
diff --git a/railties/doc/guides/actioncontroller/request_response_objects.txt b/railties/doc/guides/actioncontroller/request_response_objects.txt
new file mode 100644
index 0000000000..d335523a25
--- /dev/null
+++ b/railties/doc/guides/actioncontroller/request_response_objects.txt
@@ -0,0 +1,35 @@
+== 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.
+
+=== 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
+
+ * host - The hostname used for this request.
+ * domain - The hostname without the first part (usually "www").
+ * format - The content type requested by the client.
+ * method - The HTTP method used for the request.
+ * get?, post?, put?, delete?, head? - Returns true if the HTTP method is get/post/put/delete/head.
+ * headers - Returns a hash containing the headers associated with the request.
+ * port - The port number (integer) used for the request.
+ * protocol - The protocol used for the request.
+ * query_string - The query string part of the URL - everything after "?".
+ * remote_ip - The IP address of the client.
+ * url - The entire URL used for the request.
+
+==== path_parameters, query_parameters and request_parameters ====
+
+TODO: Does this belong here?
+
+Rails collects all of the parameters sent along with the request in the `params` hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The `query_parameters` hash contains parameters that were sent as part of the query string while the `request_parameters` hash contains parameters sent as part of the post body. The `path_parameters` hash contains parameters that were recognised by the routing as being part of the path leading to this particular controller and action.
+
+=== The response ===
+
+The response objects is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes - like in an after filter - it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values.
+
+ * body - This is the string of data being sent back to the client. This is most often HTML.
+ * status - The HTTP status code for the response, like 200 for a successful request or 404 for file not found.
+ * location - The URL the client is being redirected to, if any.
+ * content_type - The content type of the response.
+ * charset - The character set being used for the response. Default is "utf8".
diff --git a/railties/doc/guides/actioncontroller/rescue.txt b/railties/doc/guides/actioncontroller/rescue.txt
new file mode 100644
index 0000000000..6ff7ea67d8
--- /dev/null
+++ b/railties/doc/guides/actioncontroller/rescue.txt
@@ -0,0 +1,3 @@
+== Rescue ==
+
+Describe how to use rescue_from et al to rescue exceptions in controllers.
diff --git a/railties/doc/guides/actioncontroller/session.txt b/railties/doc/guides/actioncontroller/session.txt
new file mode 100644
index 0000000000..50ed76e3ae
--- /dev/null
+++ b/railties/doc/guides/actioncontroller/session.txt
@@ -0,0 +1,130 @@
+== 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.
+
+ * 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.
+
+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]
+config.action_controller.session_store = :active_record_store
+------------------------------------------
+
+=== 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:
+
+[source, ruby]
+------------------------------------------
+class ApplicationController < ActionController::Base
+
+private
+
+ # Finds the User with the ID stored in the session with the key :current_user_id
+ def current_user
+ @_current_user ||= session[:current_user_id] && User.find(session[:current_user_id])
+ end
+
+end
+------------------------------------------
+
+To store something in the session, just assign it to the key like a hash:
+
+[source, ruby]
+------------------------------------------
+class LoginsController < ApplicationController
+
+ # "Create" a login, aka "log the user in"
+ def create
+ if user = User.authenticate(params[:username, params[:password])
+ # Save the user ID in the session so it can be used in subsequent requests
+ session[:current_user_id] = user.id
+ redirect_to root_url
+ end
+ end
+
+end
+------------------------------------------
+
+To remove something from the session, assign that key to be `nil`:
+
+[source, ruby]
+------------------------------------------
+class LoginsController < ApplicationController
+
+ # "Delete" a login, aka "log the user out"
+ def destroy
+ # Remove the user id from the session
+ session[:current_user_id] = nil
+ redirect_to root_url
+ end
+
+end
+------------------------------------------
+
+To reset the entire session, use `reset_session`.
+
+=== The flash ===
+
+The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Let's use the act of logging out as an example. The controller can set a message which will be displayed to the user on the next request:
+
+[source, ruby]
+------------------------------------------
+class LoginsController < ApplicationController
+
+ def destroy
+ session[:current_user_id] = nil
+ flash[:notice] = "You have successfully logged out"
+ redirect_to root_url
+ end
+
+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>
+------------------------------------------
+
+This way, if an action sets an error or a notice message, the layout will display it automatically.
+
+If you want a flash value to be carried over to another request, use the `keep` method:
+
+[source, ruby]
+------------------------------------------
+class MainController < ApplicationController
+
+ # Let's say this action corresponds to root_url, but you want all requests here to be redirected to
+ # UsersController#index. If an action sets the flash and redirects here, the values would normally be
+ # lost when another redirect happens, but you can use keep to make it persist for another request.
+ def index
+ flash.keep # Will persist all flash values. You can also use a key to keep only that value: flash.keep(:notice)
+ redirect_to users_url
+ end
+
+end
+------------------------------------------
diff --git a/railties/doc/guides/actioncontroller/streaming.txt b/railties/doc/guides/actioncontroller/streaming.txt
new file mode 100644
index 0000000000..6026a8c51b
--- /dev/null
+++ b/railties/doc/guides/actioncontroller/streaming.txt
@@ -0,0 +1,91 @@
+== 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.
+
+To stream data to the client, use `send_data`:
+
+[source, ruby]
+----------------------------
+require "prawn"
+class ClientsController < ApplicationController
+
+ # Generate a PDF document with information on the client and return it.
+ # The user will get the PDF as a file download.
+ def download_pdf
+ client = Client.find(params[:id])
+ send_data(generate_pdf, :filename => "#{client.name}.pdf", :type => "application/pdf")
+ end
+
+private
+
+ def generate_pdf(client)
+ Prawn::Document.new do
+ text client.name, :align => :center
+ text "Address: #{client.address}"
+ text "Email: #{client.email}"
+ end.render
+ end
+
+end
+----------------------------
+
+The `download_pdf` action in the example above will call a private method which actually generates the file (a PDF document) and returns it as a string. This string will then be streamed to the client as a file download and a filename will be suggested to the user. Sometimes when streaming files to the user, you may not want them to download the file. Take images, for example, which can be embedded into HTML pages. To tell the browser a file is not meant to be downloaded, you can set the `:disposition` option to "inline". The opposite and default value for this option is "attachment".
+
+=== Sending files ===
+
+If you want to send a file that already exists on disk, use the `send_file` method. This is usually not recommended, but can be useful if you want to perform some authentication before letting the user download the file.
+
+[source, ruby]
+----------------------------
+class ClientsController < ApplicationController
+
+ # Stream a file that has already been generated and stored on disk
+ def download_pdf
+ client = Client.find(params[:id])
+ send_data("#{RAILS_ROOT}/files/clients/#{client.id}.pdf", :filename => "#{client.name}.pdf", :type => "application/pdf")
+ end
+
+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.
+
+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.
+
+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.
+
+=== 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:
+
+[source, ruby]
+----------------------------
+class ClientsController < ApplicationController
+
+ # The user can request to receive this resource as HTML or PDF.
+ def show
+ @client = Client.find(params[:id])
+
+ respond_to do |format|
+ format.html
+ format.pdf{ render :pdf => generate_pdf(@client) }
+ end
+ end
+
+end
+----------------------------
+
+In order for this example to work, we have to add the PDF MIME type to Rails. This can be done by adding the following line to the file `config/initializers/mime_types.rb`:
+
+[source, ruby]
+----------------------------
+Mime::Type.register "application/pdf", :pdf
+----------------------------
+
+NOTE: Configuration files are not reloaded on each request, so you have to restart the server in order for their changes to take effect.
+
+Now the user can request to get a PDF version of a client just by adding ".pdf" to the URL:
+
+----------------------------
+GET /clients/1.pdf
+----------------------------
diff --git a/railties/doc/guides/actioncontroller/verification.txt b/railties/doc/guides/actioncontroller/verification.txt
new file mode 100644
index 0000000000..129ff7e7b0
--- /dev/null
+++ b/railties/doc/guides/actioncontroller/verification.txt
@@ -0,0 +1,3 @@
+== Verification ==
+
+Describe how to use the verify methods to make sure some prerequisites are met before an action gets run
diff --git a/railties/doc/guides/actionview/layouts_and_rendering.txt b/railties/doc/guides/actionview/layouts_and_rendering.txt
index c21ab72ee9..5a370500e5 100644
--- a/railties/doc/guides/actionview/layouts_and_rendering.txt
+++ b/railties/doc/guides/actionview/layouts_and_rendering.txt
@@ -1,5 +1,5 @@
Layouts and Rendering in Rails
-=====================================
+==============================
This guide covers the basic layout features of Action Controller and Action View. By referring to this guide, you will be able to:
@@ -80,50 +80,637 @@ WARNING: Using +render+ with +:action+ is a frequent source of confusion for Rai
==== Using +render+ with +:template+
+What if you want to render a template from an entirely different controller from the one that contains the action code? You can do that with the +:template+ option to +render+, which accepts the full path (relative to +app/views+) of the template to render. For example, if you're running code in an +AdminProductsController+ that lives in +app/controllers/admin+, you can render the results of an action to a template in +app/views/products+ this way:
+
+[source, ruby]
+-------------------------------------------------------
+render :template => 'products/show'
+-------------------------------------------------------
+
==== Using +render+ with +:file+
+If you want to use a view that's entirely outside of your application (perhaps you're sharing views between two Rails applications), you can use the +:file+ option to +render+:
+
+[source, ruby]
+-------------------------------------------------------
+render :file => "/u/apps/warehouse_app/current/app/views/products/show"
+-------------------------------------------------------
+
+The +:file+ option takes an absolute file-system path. Of course, you need to have rights to the view that you're using to render the content.
+
+NOTE: By default, if you use the +:file+ option, the file is rendered without using the current layout. If you want Rails to put the file into the current layout, you need to add the +:layout => true+ option
+
==== Using +render+ with +:inline+
+The +render+ method can do without a view completely, if you're willing to use the +:inline+ option to supply ERB as part of the method call. This is perfectly valid:
+
+[source, ruby]
+-------------------------------------------------------
+render :inline => "<% products.each do |p| %><p><%= p.name %><p><% end %>"
+-------------------------------------------------------
+
+WARNING: There is seldom any good reason to use this option. Mixing ERB into your controllers defeats the MVC orientation of Rails and will make it harder for other developers to follow the logic of your project. Use a separate erb view instead.
+
+By default, inline rendering uses ERb. You can force it to use Builder instead with the +:type+ option:
+
+[source, ruby]
+-------------------------------------------------------
+render :inline => "xml.p {'Horrid coding practice!'}", :type => :builder
+-------------------------------------------------------
+
==== Using +render+ with +:update+
+You can also render javascript-based page updates inline using the +:update+ option to +render+:
+
+[source, ruby]
+-------------------------------------------------------
+render :update do |page|
+ page.replace_html 'warning', "Invalid options supplied"
+end
+-------------------------------------------------------
+
+WARNING: Placing javascript updates in your controller may seem to streamline small updates, but it defeats the MVC orientation of Rails and will make it harder for other developers to follow the logic of your project. I recommend using a separate rjs template instead, no matter how small the update.
+
==== Rendering Text
+You can send plain text - with no markup at all - back to the browser by using the +:text+ option to +render+:
+
+[source, ruby]
+-------------------------------------------------------
+render :text => "OK"
+-------------------------------------------------------
+
+TIP: Rendering pure text is most useful when you're responding to AJAX or web service requests that are expecting something other than proper HTML.
+
+NOTE: By default, if you use the +:text+ option, the file is rendered without using the current layout. If you want Rails to put the text into the current layout, you need to add the +:layout => true+ option
+
==== Rendering JSON
+JSON is a javascript data format used by many AJAX libraries. Rails has built-in support for converting objects to JSON and rendering that JSON back to the browser:
+
+[source, ruby]
+-------------------------------------------------------
+render :json => @product
+-------------------------------------------------------
+
+TIP: You don't need to call +to_json+ on the object that you want to render. If you use the +:json+ option, +render+ will automatically call +to_json+ for you.
+
==== Rendering XML
+Rails also has built-in support for converting objects to XML and rendering that XML back to the caller:
+
+[source, ruby]
+-------------------------------------------------------
+render :xml => @product
+-------------------------------------------------------
+
+TIP: You don't need to call +to_xml+ on the object that you want to render. If you use the +:xml+ option, +render+ will automatically call +to_xml+ for you.
+
==== Options for +render+
+Calls to the +render+ method generally accept four options:
+
+* +:content_type+
+* +:layout+
+* +:status+
+* +:location+
+
===== The +:content_type+ Option
+By default, Rails will serve the results of a rendering operation with the MIME content-type of +text/html+ (or +application/json+ if you use the +:json+ option, or +application/xml+ for the +:xml+ option.). There are times when you might like to change this, and you can do so by setting the +:content_type+ option:
+
+[source, ruby]
+-------------------------------------------------------
+render :file => filename, :content_type => 'application/rss'
+-------------------------------------------------------
+
===== The +:layout+ Option
-include :layout => false
+With most of the options to +render+, the rendered content is displayed as part of the current layout. You'll learn more about layouts and how to use them later in this guide. To find the current layout, Rails first looks for a file in +app/views/layouts+ with the same base name as the controller. For example, rendering actions from the +PhotosController+ class will use +/app/views/layouts/photos.html.erb+. If there is no such controller-specific layout, Rails will use +/app/views/layouts/application.html.erb+.
+
+You can use the +:layout+ option to tell Rails to use a specific file as the layout for the current action:
+
+[source, ruby]
+-------------------------------------------------------
+render :layout => 'special_layout'
+-------------------------------------------------------
+
+You can also tell Rails to render with no layout at all:
+
+[source, ruby]
+-------------------------------------------------------
+render :layout => false
+-------------------------------------------------------
===== The +:status+ Option
+Rails will automatically generate a response with the correct HTML status code (in most cases, this is +200 OK+). You can use the +:status+ option to change this:
+
+[source, ruby]
+-------------------------------------------------------
+render :status => 500
+render :status => :forbidden
+-------------------------------------------------------
+
+Rails understands either numeric status codes or symbols for status codes. You can find its list of status codes in +actionpack/lib/action_controller/status_codes.rb+. You can also see there how it maps symbols to status codes in that file.
+
===== The +:location+ Option
+You can use the +:location+ option to set the HTTP +Location+ header:
+
+[source, ruby]
+-------------------------------------------------------
+render :xml => photo, :location => photo_url(photo)
+-------------------------------------------------------
+
+==== Avoiding Double Render Errors
+
+Sooner or later, most Rails developers will see the error message "Can only render or redirect once per action". While this is annoying, it's relatively easy to fix. Usually it happens because of a fundamental misunderstanding of the way that +render+ works.
+
+For example, here's some code that will trigger this error:
+
+[source, ruby]
+-------------------------------------------------------
+def show
+ @book = Book.find(params[:id])
+ if @book.special?
+ render :action => "special_show"
+ end
+end
+-------------------------------------------------------
+
+If +@book.special?+ evaluates to +true+, Rails will start the rendering process to dump the +@book+ variable into the +special_show+ view. But this will _not_ stop the rest of the code in the +show+ action from running, and when Rails hits the end of the action, it will start to render the +show+ view - and throw an error. The solution is simple: make sure that you only have one call to +render+ or +redirect+ in a single code path. One thing that can help is +and return+. Here's a patched version of the method:
+
+[source, ruby]
+-------------------------------------------------------
+def show
+ @book = Book.find(params[:id])
+ if @book.special?
+ render :action => "special_show" and return
+ end
+end
+-------------------------------------------------------
+
=== Using +redirect_to+
+Another way to handle returning responses to a HTTP request is with +redirect_to+. As you've seen, +render+ tells Rails which view (or other asset) to use in constructing a response. The +redirect_to+ method does something completely different: it tells the browser to send a new request for a different URL. For example, you could redirect from wherever you are in your code to the index of photos in your application with this call:
+
+[source, ruby]
+-------------------------------------------------------
+redirect_to photos_path
+-------------------------------------------------------
+
+You can use +redirect_to+ with any arguments that you could use with +link_to+ or +url_for+. In addition, there's a special redirect that sends the user back to the page they just came from:
+
+-------------------------------------------------------
+redirect_to :back
+-------------------------------------------------------
+
==== Getting a Different Redirect Status Code
+Rails uses HTTP status code 302 (permanent redirect) when you call +redirect_to+. If you'd like to use a different status code (perhaps 301, temporary redirect), you can do so by using the +:status+ option:
+
+-------------------------------------------------------
+redirect_to photos_path, :status => 301
+-------------------------------------------------------
+
+Just like the +:status+ option for +render+, +:status+ for +redirect_to+ accepts both numeric and symbolic header designations.
+
+==== The Difference Between +render+ and +redirect+
+
+Sometimes inexperienced developers conceive of +redirect_to+ as a sort of +goto+ command, moving execution from one place to another in your Rails code. This is _not_ correct. Your code stops running and waits for a new request for the browser. It just happens that you've told the browser what request it should make next, by sending back a HTTP 302 status code.
+
+Consider these actions to see the difference:
+
+[source, ruby]
+-------------------------------------------------------
+def index
+ @books = Book.find(:all)
+end
+
+def show
+ @book = Book.find(params[:id])
+ if @book.nil?
+ render :action => "index" and return
+ end
+end
+-------------------------------------------------------
+
+With the code in this form, there will be likely be a problem if the +@book+ variable is +nil+. Remember, a +render :action+ doesn't run any code in the target action, so nothing will set up the +@books+ variable that the +index+ view is presumably depending on. One way to fix this is to redirect instead of rendering:
+
+[source, ruby]
+-------------------------------------------------------
+def index
+ @books = Book.find(:all)
+end
+
+def show
+ @book = Book.find(params[:id])
+ if @book.nil?
+ redirect_to :action => "index" and return
+ end
+end
+-------------------------------------------------------
+
+With this code, the browser will make a fresh request for the index page, the code in the +index+ method will run, and all will be well.
+
=== Using +head+ To Build Header-Only Responses
+The +head+ method exists to let you send back responses to the browser that have only headers. It provides a more obvious alternative to calling +render :nothing+. The +head+ method takes one response, which is interpreted as a hash of header names and values. For example, you can return only an error header:
+
+[source, ruby]
+-------------------------------------------------------
+head :bad_request
+-------------------------------------------------------
+
+Or you can use other HTTP headers to convey additional information:
+
+[source, ruby]
+-------------------------------------------------------
+head :created, :location => photo_path(@photo)
+-------------------------------------------------------
+
== Structuring Layouts
-=== Include Statements
+When Rails renders a view as a response, it does so by combining the view with the current layout. To find the current layout, Rails first looks for a file in +app/views/layouts+ with the same base name as the controller. For example, rendering actions from the +PhotosController+ class will use +/app/views/layouts/photos.html.erb+. If there is no such controller-specific layout, Rails will use +/app/views/layouts/application.html.erb+. You can also specify a particular layout by using the +:layout+ option to +render+.
+
+Within a layout, you have access to three tools for combining different bits of output to form the overall response:
+
+* Asset tags
+* +yield+ and +content_for+
+* Partials
+
+I'll discuss each of these in turn.
+
+=== Asset Tags
+
+Asset tags provide methods for generating HTML that links views to assets like images, javascript, stylesheets, and feeds. There are four types of include tag:
+
+* auto_discovery_link_tag
+* javascript_include_tag
+* stylesheet_link_tag
+* image_tag
+
+You can use these tags in layouts or other views, although the tags other than +image_tag+ are most commonly used in the +<head>+ section of a layout.
+
+WARNING: The asset tags do _not_ verify the existence of the assets at the specified locations; they simply assume that you know what you're doing and generate the link.
+
+==== Linking to Feeds with +auto_discovery_link_tag+
+
+The +auto_discovery_link_tag helper builds HTML that most browsers and newsreaders can use to detect the presences of RSS or ATOM feeds. It takes the type of the link (+:rss+ or +:atom+), a hash of options that are passed through to url_for, and a hash of options for the tag:
+
+[source, ruby]
+-------------------------------------------------------
+<%= auto_discovery_link_tag(:rss, {:action => "feed"}, {:title => "RSS Feed"}) %>
+-------------------------------------------------------
+
+There are three tag options available for +auto_discovery_link_tag+:
+
+* +:rel+ specifies the +rel+ value in the link (defaults to "alternate")
+* +:type+ specifies an explicit MIME type. Rails will generate an appropriate MIME type automatically
+* +:title+ specifies the title of the link
+
+==== Linking to Javascript Files with +javascript_include_tag+
+
+The +javascript_include_tag+ helper returns an HTML +<script>+ tag for each source provided. Rails looks in +public/javascripts+ for these files by default, but you can specify a full path relative to the document root, or a URL, if you prefer. For example, to include +public/javascripts/main.js+:
+
+[source, ruby]
+-------------------------------------------------------
+<%= javascript_include_tag "main" %>
+-------------------------------------------------------
+
+To include +public/javascripts/main.js+ and +public/javascripts/columns.js+:
+
+[source, ruby]
+-------------------------------------------------------
+<%= javascript_include_tag "main", "columns" %>
+-------------------------------------------------------
+
+To include +public/javascripts/main.js+ and +public/photos/columns.js+:
+
+[source, ruby]
+-------------------------------------------------------
+<%= javascript_include_tag "main", "/photos/columns" %>
+-------------------------------------------------------
+
+To include +http://example.com/main.js+:
+
+[source, ruby]
+-------------------------------------------------------
+<%= javascript_include_tag "http://example.com/main.js" %>
+-------------------------------------------------------
+
+The +defaults+ option loads the Prototype and Scriptaculous libraries:
+
+[source, ruby]
+-------------------------------------------------------
+<%= javascript_include_tag :defaults %>
+-------------------------------------------------------
+
+The +all+ option loads every javascript file in +public/javascripts+, starting with the Prototype and Scriptaculous libraries:
+
+[source, ruby]
+-------------------------------------------------------
+<%= javascript_include_tag :all %>
+-------------------------------------------------------
+
+You can supply the +:recursive+ option to load files in subfolders of +public/javascripts+ as well:
+
+[source, ruby]
+-------------------------------------------------------
+<%= javascript_include_tag :all, :recursive %>
+-------------------------------------------------------
+
+If you're loading multiple javascript files, you can create a better user experience by combining multiple files into a single download. To make this happen in production, specify +:cache => true+ in your +javascript_include_tag+:
+
+[source, ruby]
+-------------------------------------------------------
+<%= javascript_include_tag "main", "columns", :cache => true %>
+-------------------------------------------------------
+
+==== Linking to CSS Files with +stylesheet_link_tag+
+
+The +stylesheet_link_tag+ helper returns an HTML +<link>+ tag for each source provided. Rails looks in +public/stylesheets+ for these files by default, but you can specify a full path relative to the document root, or a URL, if you prefer. For example, to include +public/stylesheets/main.cs+:
+
+[source, ruby]
+-------------------------------------------------------
+<%= stylesheet_link_tag "main" %>
+-------------------------------------------------------
+
+To include +public/stylesheets/main.css+ and +public/stylesheets/columns.css+:
+
+[source, ruby]
+-------------------------------------------------------
+<%= stylesheet_link_tag "main", "columns" %>
+-------------------------------------------------------
+
+To include +public/stylesheets/main.css+ and +public/photos/columns.css+:
+
+[source, ruby]
+-------------------------------------------------------
+<%= stylesheet_link_tag "main", "/photos/columns" %>
+-------------------------------------------------------
+
+To include +http://example.com/main.cs+:
+
+[source, ruby]
+-------------------------------------------------------
+<%= stylesheet_link_tag "http://example.com/main.cs" %>
+-------------------------------------------------------
+
+By default, +stylesheet_link_tag+ creates links with +media="screen" rel="stylesheet" type="text/css"+. You can override any of these defaults by specifying an appropriate option (:media, :rel, or :type):
+
+[source, ruby]
+-------------------------------------------------------
+<%= stylesheet_link_tag "main_print", media => "print" %>
+-------------------------------------------------------
+
+The +all+ option links every CSS file in +public/stylesheets+:
+
+[source, ruby]
+-------------------------------------------------------
+<%= stylesheet_link_tag :all %>
+-------------------------------------------------------
+
+You can supply the +:recursive+ option to link files in subfolders of +public/stylesheets+ as well:
+
+[source, ruby]
+-------------------------------------------------------
+<%= stylesheet_link_tag :all, :recursive %>
+-------------------------------------------------------
+
+If you're loading multiple CSS files, you can create a better user experience by combining multiple files into a single download. To make this happen in production, specify +:cache => true+ in your +stylesheet_link_tag+:
+
+[source, ruby]
+-------------------------------------------------------
+<%= stylesheet_link_tag "main", "columns", :cache => true %>
+-------------------------------------------------------
+
+==== 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:
+
+[source, ruby]
+-------------------------------------------------------
+<%= image_tag "header" %>
+-------------------------------------------------------
+
+You can supply a path to the image if you like:
+
+[source, ruby]
+-------------------------------------------------------
+<%= image_tag "icons/delete.gif" %>
+-------------------------------------------------------
+
+You can supply a hash of additional HTML options:
+
+[source, ruby]
+-------------------------------------------------------
+<%= image_tag "icons/delete.gif", :height => 45 %>
+-------------------------------------------------------
+
+There are also three special options you can use with +image_tag+:
+
+* +:alt+ specifies the alt text for the image (which defaults to the file name of the file, capitalized and with no extension)
+* +:size+ specifies both width and height, in the format "{width}x{height}" (for example, "150x125")
+* +:mouseover+ sets an alternate image to be used when the onmouseover event is fired.
=== Understanding +yield+
+Within the context of a layout, +yield+ identifies a section where content from the view should be inserted. The simplest way to use this is to have a single +yield+, into which the entire contents of the view currently being rendered is inserted:
+
+[source, html]
+-------------------------------------------------------
+<html>
+ <head>
+ </head>
+ <body>
+ <%= yield %>
+ <hbody>
+</html>
+-------------------------------------------------------
+
+You can also create a layout with multiple yielding regions:
+
+[source, html]
+-------------------------------------------------------
+<html>
+ <head>
+ <%= yield :head %>
+ </head>
+ <body>
+ <%= yield %>
+ <hbody>
+</html>
+-------------------------------------------------------
+
+The main body of the view will always render into the unnamed +yield+. To render content into a named +yield+, you use the +content_for+ method.
+
=== Using +content_for+
+The +content_for+ method allows you to insert content into a +yield+ block in your layout. You only use +content_for+ to insert content in named yields. For example, this view would work with the layout that you just saw:
+
+[source, html]
+-------------------------------------------------------
+<% content_for :head do %>
+ <title>A simple page</title>
+<% end %>
+
+<p>Hello, Rails!</p>
+-------------------------------------------------------
+
+The result of rendering this page into the supplied layout would be this HTML:
+
+[source, html]
+-------------------------------------------------------
+<html>
+ <head>
+ <title>A simple page</title>
+ </head>
+ <body>
+ <p>Hello, Rails!</p>
+ <hbody>
+</html>
+-------------------------------------------------------
+
+The +content_for+ method is very helpful when your layout contains distinct regions such as sidebars and footers that should get their own blocks of content inserted. It's also useful for inserting tags that load page-specific javascript or css files into the header of an otherwise-generic layout.
+
=== Using Partials
-< toc tbd >
+Partial templates - usually just called "partials" - are another device for breaking apart the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.
+
+==== Naming Partials
+
+To render a partial as part of a view, you use the +render+ method within the view, and include the +:partial+ option:
+
+[source, ruby]
+-------------------------------------------------------
+<%= render :partial => "menu" %>
+-------------------------------------------------------
+
+This will render a file named +_menu.html.erb+ at that point within the view being rendered. Note the leading underscore character: partials are named with a leading underscore to distinguish them from regular views, even though they are referred to without the underscore. This holds true even when you're pulling in a partial from another folder:
+
+[source, ruby]
+-------------------------------------------------------
+<%= render :partial => "shared/menu" %>
+-------------------------------------------------------
+
+That code will pull in the partial from +app/views/shared/_menu.html.erb+.
+
+==== Using Partials to Simplify Views
+
+One way to use partials is to treat them as the equivalent of subroutines: as a way to move details out of a view so that you can grasp what's going on more easily. For example, you might have a view that looked like this:
+
+[source, html]
+-------------------------------------------------------
+<%= render :partial => "shared/ad_banner" %>
+
+<h1>Products</h1>
+
+<p>Here are a few of our fine products:</p>
+...
+
+<%= render :partial => "shared/footer" %>
+-------------------------------------------------------
+
+Here, the +_ad_banner.html.erb+ and +_footer.html.erb+ partials could contain content that is shared among many pages in your application. You don't need to see the details of these sections when you're concentrating on a particular page.
+
+TIP: For content that is shared among all pages in your application, you can use partials directly from layouts.
+
+==== Passing Local Variables
+
+You can also pass local variables into partials, making them even more powerful and flexible. For example, you can use this technique to reduce duplication between new and edit pages, while still keeping a bit of distinct content:
+
+[source, html]
+-------------------------------------------------------
+new.rhtml.erb:
+
+<h1>New zone</h1>
+<%= error_messages_for :zone %>
+<%= render :partial => "form", :locals => { :button_label => "Create zone", :zone => @zone } %>
+
+edit.html.erb:
+
+<h1>Editing zone</h1>
+<%= error_messages_for :zone %>
+<%= render :partial => "form", :locals => { :button_label => "Update zone", :zone => @zone } %>
+
+_form.html.erb:
+
+<% form_for(@zone) do |f| %>
+ <p>
+ <b>Zone name</b><br />
+ <%= f.text_field :name %>
+ </p>
+ <p>
+ <%= f.submit button_label %>
+ </p>
+<% end %>
+-------------------------------------------------------
+
+Although the same partial will be rendered into both views, the label on the submit button is controlled by a local variable passed into the partial.
+
+==== Rendering Collections
+
+Partials are very useful in rendering collections. When you pass a collection to a partial via the +:collection+ option, the partial will be inserted once for each member in the collection:
+
+[source, html]
+-------------------------------------------------------
+index.rhtml.erb:
+
+<h1>Products</h1>
+<%= render :partial => "product", :collection => @products %>
+
+_product.html.erb:
+
+<p>Product Name: <%= product.name %></p>
+-------------------------------------------------------
+
+When a partial is called with a pluralized collection, then the individual instances of the partial have access to the member of the collection being rendered via a singularized variable. In this case, the collection is +@products+, and within the +_product+ partial, you can refer to +product+ to get the instance that is being rendered.
== Changelog ==
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/15[Lighthouse ticket]
-* September 20, 2008: First draft 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 d33c0ac3cf..b91052f91f 100644
--- a/railties/doc/guides/activerecord/association_basics.txt
+++ b/railties/doc/guides/activerecord/association_basics.txt
@@ -345,6 +345,8 @@ class CreatePictures < ActiveRecord::Migration
end
-------------------------------------------------------
+image:images/polymorphic.png[Polymorphic Association Diagram]
+
=== Self Joins
In designing a data model, you will sometimes find a model that should have a relation to itself. For example, you may want to store all employees in a single database model, but be able to trace relationships such as manager and subordinates. This situation can be modeled with self-joining associations:
@@ -614,6 +616,24 @@ class Order < ActiveRecord::Base
end
-------------------------------------------------------
+The +belongs_to+ association supports these options:
+
+// * +:accessible+
+* +:class_name+
+* +:conditions+
+* +:counter_cache+
+* +:dependent+
+* +:foreign_key+
+* +:include+
+* +:polymorphic+
+* +:readonly+
+* +:select+
+* +:validate+
+
+// ===== +:accessible+
+//
+// The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass // assignment is allowed for this association.
+//
===== +: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:
@@ -636,29 +656,6 @@ class Order < ActiveRecord::Base
end
-------------------------------------------------------
-===== +:select+
-
-The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
-
-===== +:foreign_key+
-
-By convention, Rails guesses that the column used to hold the foreign key on this model is the name of the association with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
-
-[source, ruby]
--------------------------------------------------------
-class Order < ActiveRecord::Base
- belongs_to :customer, :class_name => :patron, :foreign_key => "patron_id"
-end
--------------------------------------------------------
-
-TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
-
-===== +:dependent+
-
-If you set the +:dependent+ option to +:destroy+, then deleting this object will call the destroy method on the associated object to delete that object. If you set the +:dependent+ option to +:delete+, then deleting this object will delete the associated object _without_ calling its +destroy+ method.
-
-WARNING: You should not specify this option on a +belongs_to+ association that is connected with a +has_many+ association on the other class. Doing so can lead to orphaned records in your database.
-
===== +:counter_cache+
The +:counter_cache+ option can be used to make finding the number of belonging objects more efficient. Consider these models:
@@ -703,6 +700,25 @@ Counter cache columns are added to the containing model's list of read-only attr
WARNING: When you create a counter cache column in the database, be sure to specify a default value of zero. Otherwise, Rails will not properly maintain the counter.
+===== +:dependent+
+
+If you set the +:dependent+ option to +:destroy+, then deleting this object will call the destroy method on the associated object to delete that object. If you set the +:dependent+ option to +:delete+, then deleting this object will delete the associated object _without_ calling its +destroy+ method.
+
+WARNING: You should not specify this option on a +belongs_to+ association that is connected with a +has_many+ association on the other class. Doing so can lead to orphaned records in your database.
+
+===== +:foreign_key+
+
+By convention, Rails guesses that the column used to hold the foreign key on this model is the name of the association with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
+
+[source, ruby]
+-------------------------------------------------------
+class Order < ActiveRecord::Base
+ belongs_to :customer, :class_name => :patron, :foreign_key => "patron_id"
+end
+-------------------------------------------------------
+
+TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
+
===== +:include+
You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
@@ -747,15 +763,16 @@ Passing +true+ to the +:polymorphic+ option indicates that this is a polymorphic
If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
-===== +:validate+
+===== +:select+
-If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved.
+The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
-===== +:accessible+
+===== +:validate+
-The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass assignment is allowed for this association.
+If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved.
==== When are Objects Saved?
+
Assigning an object to a +belongs_to+ association does _not_ automatically save the object. It does not save the associated object either.
=== The has_one Association
@@ -843,7 +860,6 @@ The +create__\_association__+ method returns a new object of the associated type
==== Options for +has_one+
-
In many situations, you can use the default behavior of +has_one+ without any customization. But despite Rails' emphasis of convention over customization, you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a +has_one+ association. For example, an association with several options might look like this:
[source, ruby]
@@ -853,6 +869,32 @@ class Supplier < ActiveRecord::Base
end
-------------------------------------------------------
+The +has_one+ association supports these options:
+
+// * +:accessible+
+* +:as+
+* +:class_name+
+* +:conditions+
+* +:dependent+
+* +:foreign_key+
+* +:include+
+* +:order+
+* +:primary_key+
+* +:readonly+
+* +:select+
+* +:source+
+* +:source_type+
+* +:through+
+* +:validate+
+
+// ===== +:accessible+
+//
+// The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass // assignment is allowed for this association.
+//
+===== +:as+
+
+Setting the +:as+ option indicates that this is a polymorphic association. Polymorphic associations are discussed in detail later in this guide.
+
===== +: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:
@@ -875,10 +917,6 @@ class Supplier < ActiveRecord::Base
end
-------------------------------------------------------
-===== +:order+
-
-The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause). Because a +has_one+ association will only retrieve a single associated object, this option should not be needed.
-
===== +:dependent+
If you set the +:dependent+ option to +:destroy+, then deleting this object will call the destroy method on the associated object to delete that object. If you set the +:dependent+ option to +:delete+, then deleting this object will delete the associated object _without_ calling its +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the association object to +NULL+.
@@ -896,10 +934,6 @@ end
TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
-===== +:primary_key+
-
-By convention, Rails guesses that the column used to hold the primary key of this model is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
-
===== +:include+
You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
@@ -934,17 +968,21 @@ class Representative < ActiveRecord::Base
end
-------------------------------------------------------
-===== +:as+
+===== +:order+
-Setting the +:as+ option indicates that this is a polymorphic association. Polymorphic associations are discussed in detail later in this guide.
+The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause). Because a +has_one+ association will only retrieve a single associated object, this option should not be needed.
-===== +:select+
+===== +:primary_key+
-The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
+By convention, Rails guesses that the column used to hold the primary key of this model is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
-===== +:through+
+===== +:readonly+
-The +:through+ option specifies a join model through which to perform the query. +has_one :through+ associations are discussed in detail later in this guide.
+If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
+
+===== +:select+
+
+The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
===== +:source+
@@ -954,18 +992,14 @@ The +:source+ option specifies the source association name for a +has_one :throu
The +:source_type+ option specifies the source association type for a +has_one :through+ association that proceeds through a polymorphic association.
-===== +:readonly+
+===== +:through+
-If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
+The +:through+ option specifies a join model through which to perform the query. +has_one :through+ associations are discussed in detail later in this guide.
===== +:validate+
If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved.
-===== +:accessible+
-
-The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass assignment is allowed for this association.
-
==== When are Objects Saved?
When you assign an object to a +has_one+ association, that object is automatically saved (in order to update its foreign key). In addition, any object being replaced is also automatically saved, because its foreign key will change too.
@@ -1138,6 +1172,39 @@ class Customer < ActiveRecord::Base
end
-------------------------------------------------------
+The +has_many+ association supports these options:
+
+// * +:accessible+
+* +:as+
+* +:class_name+
+* +:conditions+
+* +:counter_sql+
+* +:dependent+
+* +:extend+
+* +:finder_sql+
+* +:foreign_key+
+* +:group+
+* +:include+
+* +:limit+
+* +:offset+
+* +:order+
+* +:primary_key+
+* +:readonly+
+* +:select+
+* +:source+
+* +:source_type+
+* +:through+
+* +:uniq+
+* +:validate+
+
+// ===== +:accessible+
+//
+// The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass // assignment is allowed for this association.
+//
+===== +:as+
+
+Setting the +:as+ option indicates that this is a polymorphic association, as discussed earlier in this guide.
+
===== +: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:
@@ -1171,16 +1238,25 @@ end
If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@customer.confirmed_orders.create+ or +@customer.confirmed_orders.build+ will create orders where the confirmed column has the value +true+.
-===== +:order+
+===== +:counter_sql+
-The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause).
+Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself.
-[source, ruby]
--------------------------------------------------------
-class Customer < ActiveRecord::Base
- has_many :orders, :order => "date_confirmed DESC"
-end
--------------------------------------------------------
+NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL will be generated by substituting +SELECT COUNT(*) FROM+ for the +SELECT ... FROM+ clause of your +:finder_sql+ statement.
+
+===== +:dependent+
+
+If you set the +:dependent+ option to +:destroy+, then deleting this object will call the destroy method on the associated objects to delete those objects. If you set the +:dependent+ option to +:delete_all+, then deleting this object will delete the associated objects _without_ calling their +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the associated objects to +NULL+.
+
+NOTE: This option is ignored when you use the +:through+ option on the association.
+
+===== +:extend+
+
+The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.
+
+===== +:finder_sql+
+
+Normally Rails automatically generates the proper SQL to fetch the association members. With the +:finder_sql+ option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.
===== +:foreign_key+
@@ -1195,29 +1271,16 @@ end
TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
-===== +:primary_key+
-
-By convention, Rails guesses that the column used to hold the primary key of this model is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
-
-===== +:dependent+
-
-If you set the +:dependent+ option to +:destroy+, then deleting this object will call the destroy method on the associated objects to delete those objects. If you set the +:dependent+ option to +:delete_all+, then deleting this object will delete the associated objects _without_ calling their +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the associated objects to +NULL+.
-
-NOTE: This option is ignored when you use the +:through+ option on the association.
-
-===== +:finder_sql+
-
-Normally Rails automatically generates the proper SQL to fetch the association members. With the +:finder_sql+ option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.
-
-===== +:counter_sql+
-
-Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself.
-
-NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL will be generated by substituting +SELECT COUNT(*) FROM+ for the +SELECT ... FROM+ clause of your +:finder_sql+ statement.
+===== +:group+
-===== +:extend+
+The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.
-The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.
+[source, ruby]
+-------------------------------------------------------
+class Customer < ActiveRecord::Base
+ has_many :line_items, :through => :orders, :group => "orders.id"
+end
+-------------------------------------------------------
===== +:include+
@@ -1253,31 +1316,39 @@ class LineItem < ActiveRecord::Base
end
-------------------------------------------------------
-===== +:group+
+===== +:limit+
-The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.
+The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.
[source, ruby]
-------------------------------------------------------
class Customer < ActiveRecord::Base
- has_many :line_items, :through => :orders, :group => "orders.id"
+ has_many :recent_orders, :class_name => :orders, :order => "order_date DESC", :limit => 100
end
-------------------------------------------------------
-===== +:limit+
+===== +:offset+
-The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.
+The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 10 records.
+
+===== +:order+
+
+The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause).
[source, ruby]
-------------------------------------------------------
class Customer < ActiveRecord::Base
- has_many :recent_orders, :class_name => :orders, :order => "order_date DESC", :limit => 100
+ has_many :orders, :order => "date_confirmed DESC"
end
-------------------------------------------------------
-===== +:offset+
+===== +:primary_key+
-The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 10 records.
+By convention, Rails guesses that the column used to hold the primary key of this model is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
+
+===== +:readonly+
+
+If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.
===== +:select+
@@ -1285,14 +1356,6 @@ The +:select+ option lets you override the SQL +SELECT+ clause that is used to r
WARNING: If you specify your own +:select+, be sure to include the primary key and foreign key columns of the associated model. If you do not, Rails will throw an error.
-===== +:as+
-
-Setting the +:as+ option indicates that this is a polymorphic association, as discussed earlier in this guide.
-
-===== +:through+
-
-The +:through+ option specifies a join model through which to perform the query. +has_many :through+ associations provide a way to implement many-to-many relationships, as discussed earlier in this guide.
-
===== +:source+
The +:source+ option specifies the source association name for a +has_many :through+ association. You only need to use this option if the name of the source association cannot be automatically inferred from the association name.
@@ -1301,22 +1364,18 @@ The +:source+ option specifies the source association name for a +has_many :thro
The +:source_type+ option specifies the source association type for a +has_many :through+ association that proceeds through a polymorphic association.
-===== +:uniq+
+===== +:through+
-Specify the +:uniq => true+ option to remove duplicates from the collection. This is most useful in conjunction with the +:through+ option.
+The +:through+ option specifies a join model through which to perform the query. +has_many :through+ associations provide a way to implement many-to-many relationships, as discussed earlier in this guide.
-===== +:readonly+
+===== +:uniq+
-If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.
+Specify the +:uniq => true+ option to remove duplicates from the collection. This is most useful in conjunction with the +:through+ option.
===== +:validate+
If you set the +:validate+ option to +false+, then associated objects will not be validated whenever you save this object. By default, this is +true+: associated objects will be validated when this object is saved.
-===== +:accessible+
-
-The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass assignment is allowed for this association.
-
==== When are Objects Saved?
When you assign an object to a +has_many+ association, that object is automatically saved (in order to update its foreign key). If you assign multiple objects in one statement, then they are all saved.
@@ -1498,25 +1557,33 @@ class Parts < ActiveRecord::Base
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:
-
-[source, ruby]
--------------------------------------------------------
-class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :class_name => :gadgets
-end
--------------------------------------------------------
-
-===== +:join_table+
-
-If the default name of the join table, based on lexical ordering, is not what you want, you can use the +:join_table+ option to override the default.
-
-===== +:foreign_key+
-
-By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to this model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
-
+The +has_and_belongs_to_many+ association supports these options:
+
+// * +:accessible+
+* +:association_foreign_key+
+* +:class_name+
+* +:conditions+
+* +:counter_sql+
+* +:delete_sql+
+* +:extend+
+* +:finder_sql+
+* +:foreign_key+
+* +:group+
+* +:include+
+* +:insert_sql+
+* +:join_table+
+* +:limit+
+* +:offset+
+* +:order+
+* +:readonly+
+* +:select+
+* +:uniq+
+* +:validate+
+
+// ===== +:accessible+
+//
+// The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass // assignment is allowed for this association.
+//
===== +:association_foreign_key+
By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to the other model is the name of that model with the suffix +_id+ added. The +:association_foreign_key+ option lets you set the name of the foreign key directly:
@@ -1531,47 +1598,38 @@ class User < ActiveRecord::Base
end
-------------------------------------------------------
-===== +:conditions+
+===== +:class_name+
-The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
+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:
[source, ruby]
-------------------------------------------------------
class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :conditions => "factory = 'Seattle'"
+ has_and_belongs_to_many :assemblies, :class_name => :gadgets
end
-------------------------------------------------------
-You can also set conditions via a hash:
+===== +:conditions+
+
+The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
[source, ruby]
-------------------------------------------------------
class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :conditions => { :factory => 'Seattle' }
+ has_and_belongs_to_many :assemblies, :conditions => "factory = 'Seattle'"
end
-------------------------------------------------------
-If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@parts.assemblies.create+ or +@parts.assemblies.build+ will create orders where the factory column has the value "Seattle".
-
-===== +:order+
-
-The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause).
-
+You can also set conditions via a hash:
[source, ruby]
-------------------------------------------------------
class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :order => "assembly_name ASC"
+ has_and_belongs_to_many :assemblies, :conditions => { :factory => 'Seattle' }
end
-------------------------------------------------------
-===== +:uniq+
-
-Specify the +:uniq => true+ option to remove duplicates from the collection.
-
-===== +:finder_sql+
-
-Normally Rails automatically generates the proper SQL to fetch the association members. With the +:finder_sql+ option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.
+If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@parts.assemblies.create+ or +@parts.assemblies.build+ will create orders where the factory column has the value "Seattle".
===== +:counter_sql+
@@ -1583,17 +1641,25 @@ NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL
Normally Rails automatically generates the proper SQL to remove links between the associated classes. With the +:delete_sql+ option, you can specify a complete SQL statement to delete them yourself.
-===== +:insert_sql+
-
-Normally Rails automatically generates the proper SQL to create links between the associated classes. With the +:insert_sql+ option, you can specify a complete SQL statement to insert them yourself.
-
===== +:extend+
The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.
-===== +:include+
+===== +:finder_sql+
-You can use the :include option to specify second-order associations that should be eager-loaded when this association is used.
+Normally Rails automatically generates the proper SQL to fetch the association members. With the +:finder_sql+ option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.
+
+===== +:foreign_key+
+
+By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to this model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
+
+[source, ruby]
+-------------------------------------------------------
+class User < ActiveRecord::Base
+ has_and_belongs_to_many :friends, :class_name => :users,
+ :foreign_key => "this_user_id", :association_foreign_key => "other_user_id"
+end
+-------------------------------------------------------
===== +:group+
@@ -1606,6 +1672,18 @@ class Parts < ActiveRecord::Base
end
-------------------------------------------------------
+===== +:include+
+
+You can use the :include option to specify second-order associations that should be eager-loaded when this association is used.
+
+===== +:insert_sql+
+
+Normally Rails automatically generates the proper SQL to create links between the associated classes. With the +:insert_sql+ option, you can specify a complete SQL statement to insert them yourself.
+
+===== +:join_table+
+
+If the default name of the join table, based on lexical ordering, is not what you want, you can use the +:join_table+ option to override the default.
+
===== +:limit+
The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.
@@ -1621,22 +1699,32 @@ end
The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 10 records.
-===== +:select+
+===== +:order+
-The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.
+The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause).
+
+[source, ruby]
+-------------------------------------------------------
+class Parts < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies, :order => "assembly_name ASC"
+end
+-------------------------------------------------------
===== +:readonly+
If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.
-===== +:validate+
+===== +:select+
-If you set the +:validate+ option to +false+, then associated objects will not be validated whenever you save this object. By default, this is +true+: associated objects will be validated when this object is saved.
+The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.
-===== +:accessible+
+===== +:uniq+
-The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass assignment is allowed for this association.
+Specify the +:uniq => true+ option to remove duplicates from the collection.
+===== +:validate+
+
+If you set the +:validate+ option to +false+, then associated objects will not be validated whenever you save this object. By default, this is +true+: associated objects will be validated when this object is saved.
==== When are Objects Saved?
@@ -1746,5 +1834,6 @@ Extensions can refer to the internals of the association proxy using these three
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/11[Lighthouse ticket]
-* September 14, 2008: initial version by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
+* September 28, 2008: Corrected +has_many :through+ diagram, added polymorphic diagram, some reorganization by link:../authors.html#mgunderloy[Mike Gunderloy] . First release version.
* September 22, 2008: Added diagrams, misc. cleanup by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
+* September 14, 2008: initial version by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
diff --git a/railties/doc/guides/activerecord/images/has_many_through.png b/railties/doc/guides/activerecord/images/has_many_through.png
index 9872201416..85d7599925 100644
--- a/railties/doc/guides/activerecord/images/has_many_through.png
+++ b/railties/doc/guides/activerecord/images/has_many_through.png
Binary files differ
diff --git a/railties/doc/guides/activerecord/images/polymorphic.png b/railties/doc/guides/activerecord/images/polymorphic.png
new file mode 100644
index 0000000000..ff2fd9f76d
--- /dev/null
+++ b/railties/doc/guides/activerecord/images/polymorphic.png
Binary files differ
diff --git a/railties/doc/guides/benchmarking_and_profiling/examples/.DS_Store b/railties/doc/guides/benchmarking_and_profiling/examples/.DS_Store
deleted file mode 100644
index 5008ddfcf5..0000000000
--- a/railties/doc/guides/benchmarking_and_profiling/examples/.DS_Store
+++ /dev/null
Binary files differ
diff --git a/railties/doc/guides/benchmarking_and_profiling/rubyprof.txt b/railties/doc/guides/benchmarking_and_profiling/rubyprof.txt
index 2dd5f2a99a..fa01d413a1 100644
--- a/railties/doc/guides/benchmarking_and_profiling/rubyprof.txt
+++ b/railties/doc/guides/benchmarking_and_profiling/rubyprof.txt
@@ -8,7 +8,7 @@ One of the things that is important to us is how long it takes to render the hom
In the terminal run
-[source, bash]
+[source, ruby]
----------------------------------------------------------------------------
[User profiling_tester]$ gcruby tests/performance/homepage.rb
----------------------------------------------------------------------------
diff --git a/railties/doc/guides/debugging/debugging_rails_applications.txt b/railties/doc/guides/debugging/debugging_rails_applications.txt
index 37d4dd19d6..f7538cd08b 100644
--- a/railties/doc/guides/debugging/debugging_rails_applications.txt
+++ b/railties/doc/guides/debugging/debugging_rails_applications.txt
@@ -614,4 +614,4 @@ set listsize 25
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/5[Lighthouse ticket]
-* September 16, 2008: initial version by link:../authors.html#miloops[Emilio Tagua] \ No newline at end of file
+* September 16, 2008: initial version by link:../authors.html#miloops[Emilio Tagua]
diff --git a/railties/doc/guides/index.txt b/railties/doc/guides/index.txt
index 78228ea4a0..ad82aea3ec 100644
--- a/railties/doc/guides/index.txt
+++ b/railties/doc/guides/index.txt
@@ -3,66 +3,91 @@ Ruby on Rails guides
WARNING: This page is the result of ongoing http://hackfest.rubyonrails.org/guide[Rails Guides hackfest] and a work in progress.
+CAUTION: Guides marked with this icon are currently being worked on. While they might still be useful to you, they may contain incomplete information and even errors. You can help by reviewing them and posting your comments and corrections at the respective Lighthouse ticket.
+
++++++++++++++++++++++++++++++++++++++
-<h2>Finished Guides</h2>
+<h2>Start Here</h2>
++++++++++++++++++++++++++++++++++++++
-These guides are complete and the authors are listed link:authors.html[here].
+.link:getting_started_with_rails/getting_started_with_rails.html[Getting Started with Rails]
+***********************************************************
+CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/2[Lighthouse Ticket]
+
+Everything you need to know to install Rails and create your first application.
+***********************************************************
+
+++++++++++++++++++++++++++++++++++++++
+<h2>Models</h2>
+++++++++++++++++++++++++++++++++++++++
.link:migrations/migrations.html[Rails Database Migrations]
***********************************************************
-TODO: Insert some description here.
+This guide covers how you can use Active Record migrations to alter your database in a structured and organized manner.
***********************************************************
-.link:routing/routing_outside_in.html[Rails Routing from the Outside In]
+.link:activerecord/association_basics.html[Active Record Associations]
***********************************************************
-This guide covers the user-facing features of Rails routing. If you want to
-understand how to use routing in your own Rails applications, start here.
+This guide covers all the associations provided by Active Record.
+***********************************************************
+
+.link:activerecord/finders.html[Active Record Finders]
+***********************************************************
+CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/16[Lighthouse Ticket]
+
+This guide covers the find method defined in ActiveRecord::Base, as well as named scopes.
***********************************************************
++++++++++++++++++++++++++++++++++++++
-<h2>Guides in progress</h2>
+<h2>Views</h2>
++++++++++++++++++++++++++++++++++++++
-These guides are currently being worked on. While they still might be useful to you, you could always help by reviewing them and posting your
-findings at the respective Lighthouse ticket.
-
-.link:debugging/debugging_rails_applications.html[Debugging Rails Applications]
+.link:actionview/layouts_and_rendering.html[Layouts and Rendering in Rails]
***********************************************************
-link:http://rails.lighthouseapp.com/projects/16213/tickets/5[Lighthouse Ticket]
+CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/15[Lighthouse Ticket]
-This guide describes how to debug Rails applications. It covers the different
-ways of achieving this and how to understand what is happening "behind the scenes"
-of your code.
+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.
***********************************************************
-.link:getting_started_with_rails/getting_started_with_rails.html[Getting Started with Rails]
+.link:forms/form_helpers.html[Action View Form Helpers]
***********************************************************
-link:http://rails.lighthouseapp.com/projects/16213/tickets/2[Lighthouse Ticket]
+CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/1[Lighthouse Ticket]
+
+Guide to using built in Form helpers.
***********************************************************
-.link:activerecord/association_basics.html[Active Record Associations]
+++++++++++++++++++++++++++++++++++++++
+<h2>Controllers</h2>
+++++++++++++++++++++++++++++++++++++++
+
+.link:routing/routing_outside_in.html[Rails Routing from the Outside In]
***********************************************************
-link:http://rails.lighthouseapp.com/projects/16213/tickets/11[Lighthouse Ticket]
+This guide covers the user-facing features of Rails routing. If you want to
+understand how to use routing in your own Rails applications, start here.
***********************************************************
-.link:forms/form_helpers.html[Action View Form Helpers]
+.link:actioncontroller/actioncontroller.html[Basics of Action Controller]
***********************************************************
-link:http://rails.lighthouseapp.com/projects/16213/tickets/1[Lighthouse Ticket]
+CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/17[Lighthouse Ticket]
-Guide to using built in Form helpers.
+This guide covers how controllers work and how they fit into the request cycle in your application. It includes sessions, filters, and cookies, data streaming, and dealing with exceptions raised by a request, among other topics.
***********************************************************
-.link:benchmarking_and_profiling/preamble.html[Benchmarking and Profiling Rails Applications]
+.link:caching/caching_with_rails.html[Rails Caching]
***********************************************************
-link:http://rails.lighthouseapp.com/projects/16213/tickets/4[Lighthouse Ticket]
+CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/10[Lighthouse Ticket]
-TODO: Insert some description here.
+This guide covers the three types of caching that Rails provides by default.
***********************************************************
+++++++++++++++++++++++++++++++++++++++
+<h2>Digging Deeper</h2>
+++++++++++++++++++++++++++++++++++++++
+
.link:testing_rails_applications/testing_rails_applications.html[Testing Rails Applications]
***********************************************************
-link:http://rails.lighthouseapp.com/projects/16213/tickets/8[Lighthouse Ticket]
+CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/8[Lighthouse Ticket]
This is a rather comprehensive guide to doing both unit and functional tests
in Rails. It covers everything from ``What is a test?'' to the testing APIs.
@@ -71,20 +96,31 @@ Enjoy.
.link:securing_rails_applications/security.html[Securing Rails Applications]
***********************************************************
-link:http://rails.lighthouseapp.com/projects/16213/tickets/7[Lighthouse Ticket]
+CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/7[Lighthouse Ticket]
This manual describes common security problems in web applications and how to
avoid them with Rails.
***********************************************************
-.link:caching/caching_with_rails.html[Rails Caching]
+.link:debugging/debugging_rails_applications.html[Debugging Rails Applications]
+***********************************************************
+CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/5[Lighthouse Ticket]
+
+This guide describes how to debug Rails applications. It covers the different
+ways of achieving this and how to understand what is happening "behind the scenes"
+of your code.
+***********************************************************
+
+.link:benchmarking_and_profiling/preamble.html[Benchmarking and Profiling Rails Applications]
***********************************************************
-link:http://rails.lighthouseapp.com/projects/16213/tickets/10[Lighthouse Ticket]
+CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/4[Lighthouse Ticket]
-TODO: Insert some description here.
+This guide covers ways to analyze and optimize your running Rails code.
***********************************************************
.link:creating_plugins/creating_plugins.html[The Basics of Creating Rails Plugins]
***********************************************************
-TODO: Insert some description here. No Lighthouse ticket.
+This guide covers how to build a plugin to extend the functionality of Rails.
***********************************************************
+
+Authors who have contributed to complete guides are listed link:authors.html[here].
diff --git a/railties/doc/guides/migrations/migrations.txt b/railties/doc/guides/migrations/migrations.txt
index 653fa818dd..be183e8597 100644
--- a/railties/doc/guides/migrations/migrations.txt
+++ b/railties/doc/guides/migrations/migrations.txt
@@ -19,4 +19,4 @@ include::rakeing_around.txt[]
include::using_models_in_migrations.txt[]
include::scheming.txt[]
include::foreign_keys.txt[]
-include::changelog.txt[] \ No newline at end of file
+include::changelog.txt[]
diff --git a/railties/doc/guides/routing/routing_outside_in.txt b/railties/doc/guides/routing/routing_outside_in.txt
index fcd435ce66..2c1870d9d4 100644
--- a/railties/doc/guides/routing/routing_outside_in.txt
+++ b/railties/doc/guides/routing/routing_outside_in.txt
@@ -195,7 +195,7 @@ You can also apply RESTful routing to singleton resources within your applicatio
map.resource :geocoder
-------------------------------------------------------
-creates seven different routes in your application:
+creates six different routes in your application:
[grid="all"]
`----------`---------------`-----------`--------`-------------------------------------------
@@ -256,7 +256,7 @@ PUT /photos/1 Images update update a specific image
DELETE /photos/1 Images destroy delete a specific image
--------------------------------------------------------------------------------------------
-NOTE: The helpers will be generated with the name of the resource, not the name of the controller. So in this case, you'd still get +photos_path+, +photos_new_path+, and so on.
+NOTE: The helpers will be generated with the name of the resource, not the name of the controller. So in this case, you'd still get +photos_path+, +new_photo_path+, and so on.
=== Controller Namespaces and Routing ===
@@ -321,7 +321,7 @@ PUT /images/1 Photos update update a specific photo
DELETE /images/1 Photos destroy delete a specific photo
--------------------------------------------------------------------------------------------
-NOTE: The helpers will be generated with the name of the resource, not the path name. So in this case, you'd still get +photos_path+, +photos_new_path+, and so on.
+NOTE: The helpers will be generated with the name of the resource, not the path name. So in this case, you'd still get +photos_path+, +new_photo_path+, and so on.
==== Using :path_names
@@ -376,7 +376,7 @@ map.resources :photos, :path_prefix => '/photographers/:photographer_id', :name_
map.resources :photos, :path_prefix => '/agencies/:agency_id', :name_prefix => 'agency_'
-------------------------------------------------------
-This combination will give you route helpers such as +photographer_photos_path+ and +agency_photo_edit_path+ to use in your code.
+This combination will give you route helpers such as +photographer_photos_path+ and +agency_edit_photo_path+ to use in your code.
=== Nested Resources
@@ -537,8 +537,8 @@ It's possible to do some quite complex things by combining +:path_prefix+ and +:
[source, ruby]
-------------------------------------------------------
map.resources :photos, :path_prefix => 'admin', :controller => 'admin/photos'
-map.resources :tags, :path_prefix => 'admin_photo_', :path_prefix => 'admin/photos/:photo_id', :controller => 'admin/photo_tags'
-map.resources :ratings, :path_prefix => 'admin_photo_', :path_prefix => 'admin/photos/:photo_id', :controller => 'admin/photo_ratings'
+map.resources :tags, :name_prefix => 'admin_photo_', :path_prefix => 'admin/photos/:photo_id', :controller => 'admin/photo_tags'
+map.resources :ratings, :name_prefix => 'admin_photo_', :path_prefix => 'admin/photos/:photo_id', :controller => 'admin/photo_ratings'
-------------------------------------------------------
The good news is that if you find yourself using this level of complexity, you can stop. Rails supports _namespaced resources_ to make placing resources in their own folder a snap. Here's the namespaced version of those same three routes:
@@ -551,7 +551,7 @@ map.namespace(:admin) do |admin|
end
-------------------------------------------------------
-As you can see, the namespaced version is much more succinct than the one that spells everything out - but it still creates the same routes. For example, you'll get +admin_photos_url+ that expects to find an +Admin::PhotosController+ and that matches +admin/photos+, and +admin_photos_ratings+path+ that matches +/admin/photos/_photo_id_/ratings+, expecting to use +Admin::RatingsController+.
+As you can see, the namespaced version is much more succinct than the one that spells everything out - but it still creates the same routes. For example, you'll get +admin_photos_url+ that expects to find an +Admin::PhotosController+ and that matches +admin/photos+, and +admin_photos_ratings+path+ that matches +/admin/photos/_photo_id_/ratings+, expecting to use +Admin::RatingsController+. Even though you're not specifying +path_prefix+ explicitly, the routing code will calculate the appropriate +path_prefix+ from the route nesting.
=== Adding More RESTful Actions
@@ -905,4 +905,4 @@ assert_routing { :path => "photos", :method => :post }, { :controller => "photos
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/3[Lighthouse ticket]
* September 10, 2008: initial version by link:../authors.html#mgunderloy[Mike Gunderloy]
-* September 23, 2008: Added section on namespaced controllers and routing, by link:../authors.html#mgunderloy[Mike Gunderloy] \ No newline at end of file
+* September 23, 2008: Added section on namespaced controllers and routing, by link:../authors.html#mgunderloy[Mike Gunderloy]
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 254fd99357..11ff2e6a41 100644
--- a/railties/doc/guides/testing_rails_applications/testing_rails_applications.txt
+++ b/railties/doc/guides/testing_rails_applications/testing_rails_applications.txt
@@ -2,15 +2,18 @@ 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
* Write unit, functional and integration tests for your application
* Read about other popular testing approaches and plugins
Assumptions:
+
* 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.
* By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring.
@@ -63,7 +66,7 @@ The 'unit' folder is meant to hold tests for your models, 'functional' folder is
==== What They Are ====
-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.
@@ -92,7 +95,7 @@ Each fixture is given a 'name' followed by an indented list of colon-separated k
==== 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 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:
@@ -111,7 +114,7 @@ The first line is the header. It is a comma-separated list of fields. The rest o
* don't use blank lines
* nulls can be achived by just placing a comma, for example, (1,sclaus,,false,) minus the parenthesis of course.
-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 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
@@ -497,7 +500,11 @@ You would get to see the usage of some of these assertions in the next chapter.
== 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. Thus, you should test for things such as:
+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.
+
+=== 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?
@@ -569,7 +576,7 @@ For those of you familiar with HTTP protocol, you'll know that get is a type of
* head
* delete
-All of request types are methods that you can use, however, you'll probably end up using the first two more ofter than the others.
+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 ===
@@ -577,27 +584,26 @@ After the request has been made by using one of the 5 methods (get, post, etc…
They are (starring in alphabetical order):
-assigns
+`assigns`::
Any objects that are stored as instance variables in actions for use in views.
-cookies
+`cookies`::
Any objects cookies that are set.
-flash
+`flash`::
Any objects living in the flash.
-session
+`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:
-flash["gordon"] flash[:gordon]
-session["shmession"] session[:shmession]
-cookies["are_good_for_u"] cookies[:are_good_for_u]
+ 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)
+ assigns["something"] assigns(:something)
=== Instance variables available ===
@@ -618,14 +624,58 @@ Another example that uses flash, assert_redirected_to, assert_difference
end
--------------------------------------------------
-=== Testing Views using assert_select ===
-http://api.rubyonrails.org/classes/ActionController/Assertions/SelectorAssertions.html#M000749
+=== 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.
+
+[NOTE]
+`assert_tag` is now deprecated in favor 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(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:
+
+[source,ruby]
+--------------------------------------------------
+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.
+
+[source,ruby]
+--------------------------------------------------
+assert_select 'ul.navigation' do
+ assert_select 'li.menu_item'
+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.
==== Additional view based assertions ====
- * assert_select_rjs
- * assert_select_email
- * assert_select_encoded
+`assert_select_email`::
+Allows you to make assertions on the body of an e-mail.
+
+[source,ruby]
+--------------------------------------------------
+assert_select_email do
+ assert_select 'small', 'Please click the "Unsubscribe" link if you want to opt-out.'
+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 ==
@@ -660,25 +710,30 @@ end
* 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
-
-== Guide TODO ==
- * What to test in unit tests
- * Testing views (assert_select)
- * Examples for integration test
- * Updating Rake tasks
- * Update sectino on testing file uploads
- * Updating the section on testing mailers
-
-== Rake tasks related to testing
-
-rake db:test:*
-
-rake test
-rake test:units
-rake test:functionals
-rake test:integration
-rake test:plugin
-
+== Rake Tasks for Testing
+
+The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project.
+
+.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`
== Testing Your Mailers ==
@@ -877,3 +932,7 @@ class ActionMailer::Base
end
----------------------------------------------------------------
+== Guide TODO ==
+ * Describe _setup_ and _teardown_
+ * Examples for integration test
+ * Updating the section on testing mailers