提交 9cb54008 编写于 作者: P Pratik Naik

Merge docrails

上级 517bc500
......@@ -514,7 +514,7 @@ class << self # Class methods
#
# ==== Parameters
#
# * <tt>:conditions</tt> - An SQL fragment like "administrator = 1" or <tt>[ "user_name = ?", username ]</tt>. See conditions in the intro.
# * <tt>:conditions</tt> - An SQL fragment like "administrator = 1", <tt>[ "user_name = ?", username ]</tt>, or <tt>["user_name = :user_name", { :user_name => user_name }]</tt>. See conditions in the intro.
# * <tt>:order</tt> - An SQL fragment like "created_at DESC, name".
# * <tt>:group</tt> - An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
# * <tt>:limit</tt> - An integer determining the limit on the number of rows that should be returned.
......@@ -551,6 +551,7 @@ class << self # Class methods
# # find first
# Person.find(:first) # returns the first object fetched by SELECT * FROM people
# Person.find(:first, :conditions => [ "user_name = ?", user_name])
# Person.find(:first, :conditions => [ "user_name = :u", { :u => user_name }])
# Person.find(:first, :order => "created_on DESC", :offset => 5)
#
# # find last
......
......@@ -5,7 +5,7 @@ module ActiveRecord
# before or after an alteration of the object state. This can be used to make sure that associated and
# dependent objects are deleted when +destroy+ is called (by overwriting +before_destroy+) or to massage attributes
# before they're validated (by overwriting +before_validation+). As an example of the callbacks initiated, consider
# the <tt>Base#save</tt> call:
# the <tt>Base#save</tt> call for a new record:
#
# * (-) <tt>save</tt>
# * (-) <tt>valid</tt>
......@@ -22,7 +22,8 @@ module ActiveRecord
# * (8) <tt>after_save</tt>
#
# That's a total of eight callbacks, which gives you immense power to react and prepare for each state in the
# Active Record lifecycle.
# Active Record lifecycle. The sequence for calling <tt>Base#save</tt> an existing record is similar, except that each
# <tt>_on_create</tt> callback is replaced by the corresponding <tt>_on_update</tt> callback.
#
# Examples:
# class CreditCard < ActiveRecord::Base
......
......@@ -15,6 +15,8 @@ include::cookies.txt[]
include::filters.txt[]
include::verification.txt[]
include::request_response_objects.txt[]
include::http_auth.txt[]
......@@ -23,6 +25,4 @@ include::streaming.txt[]
include::parameter_filtering.txt[]
include::verification.txt[]
include::rescue.txt[]
......@@ -2,22 +2,30 @@
Your application can store small amounts of data on the client - called cookies - that will be persisted across requests and even sessions. Rails provides easy access to cookies via the `cookies` method, which - much like the `session` - works like a hash:
TODO: Find a real-world example where cookies are used
[source, ruby]
-----------------------------------------
class FooController < ApplicationController
def foo
cookies[:foo] = "bar"
end
class CommentsController < ApplicationController
def display_foo
@foo = cookies[:foo]
def new
#Auto-fill the commenter's name if it has been stored in a cookie
@comment = Comment.new(:name => cookies[:commenter_name])
end
def remove_foo
cookies.delete(:foo)
def create
@comment = Comment.new(params[:comment])
if @comment.save
flash[:notice] = "Thanks for your comment!"
if params[:remember_name]
# Remember the commenter's name
cookies[:commenter_name] = @comment.name
else
# Don't remember, and delete the name if it has been remembered before
cookies.delete(:commenter_name)
end
redirect_to @comment.article
else
render :action => "new"
end
end
end
......
......@@ -27,7 +27,7 @@ private
end
---------------------------------
The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a before filter (a filter which is run before the action) renders or redirects, the action will not run. If there are additional filters scheduled to run after the rendering/redirecting filter, they are also cancelled. To use this filter in a controller, use the "before_filter":http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000704 method:
The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a before filter (a filter which is run before the action) renders or redirects, the action will not run. If there are additional filters scheduled to run after the rendering/redirecting filter, they are also cancelled. To use this filter in a controller, use the link:http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000704[before_filter] method:
[source, ruby]
---------------------------------
......@@ -38,7 +38,7 @@ class ApplicationController < ActionController::Base
end
---------------------------------
In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this, so to prevent this filter from running you can use "skip_before_filter":http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000711 :
In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this, so to prevent this filter from running you can use link:http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000711[skip_before_filter] :
[source, ruby]
---------------------------------
......@@ -59,24 +59,27 @@ TODO: Find a real example for an around filter
[source, ruby]
---------------------------------
# Example taken from the Rails API filter documentation:
# http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html
class ApplicationController < Application
around_filter :foo
around_filter :catch_exceptions
private
def foo
logger.debug("Action has not been run yet")
yield #Run the action
logger.debug("Action has been run")
def catch_exceptions
yield
rescue => exception
logger.debug "Caught exception! #{exception}"
raise
end
end
---------------------------------
=== Other types of filters ===
=== Other ways to use filters ===
While the most common way to use filters is by creating private methods and using *_filter to add them, there are two other ways.
While the most common way to use filters is by creating private methods and using *_filter to add them, there are two other ways to do the same thing.
The first is to use a block directly with the *_filter methods. The block receives the controller as an argument, and the `require_login` filter from above could be rewritte to use a block:
......@@ -115,4 +118,4 @@ end
Again, this is not an ideal example for this filter, because it's not run in the scope of the controller but gets it passed as an argument. The filter class has a class method `filter` which gets run before or after the action, depending on if it's a before or after filter. Classes used as around filters can also use the same `filter` method, which will get run in the same way. The method must `yield` to execute the action. Alternatively, it can have both a `before` and an `after` method that are run before and after the action.
The Rails API documentation has "more information and detail on using filters":http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html
The Rails API documentation has link:http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html[more information on using filters].
== HTTP Basic Authentication ==
Rails comes with built-in HTTP Basic authentication. This is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, we will create an administration section which will only be available by entering a username and a password into the browser's HTTP Basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, "authenticate_or_request_with_http_basic":http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Basic/ControllerMethods.html#M000610
Rails comes with built-in HTTP Basic authentication. This is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, we will create an administration section which will only be available by entering a username and a password into the browser's HTTP Basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, link:http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Basic/ControllerMethods.html#M000610[authenticate_or_request_with_http_basic].
[source, ruby]
-------------------------------------
......
......@@ -2,6 +2,6 @@
Action Controller is the C in MVC. After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output. Luckily, Action Controller does most of the groundwork for you and uses smart conventions to make this as straight-forward as possible.
For most conventional RESTful applications, the controller will receive the request (this is invisible to the developer), fetch or save data from a model and use a view to create HTML output. If your controller needs to do things a little differently, that's not a problem, this is just the most common way for a controller to work.
For most conventional RESTful applications, the controller will receive the request (this is invisible to you as the developer), fetch or save data from a model and use a view to create HTML output. If your controller needs to do things a little differently, that's not a problem, this is just the most common way for a controller to work.
A controller can thus be thought of as a middle man between models and views. It makes the model data available to the view so it can display it to the user, and it saves or updates data from the user to the model.
== Methods and actions ==
A controller is a Ruby class which inherits from ActionController::Base and has methods just like any other class. Usually these methods correspond to actions in MVC, but they can just as well be helpful methods which can be called by actions. When your application receives a request, the routing will determine which controller and action to run. Then an instance of that controller will be created and the method corresponding to the action (the method with the same name as the action) is run.
A controller is a Ruby class which inherits from ActionController::Base and has methods just like any other class. Usually these methods correspond to actions in MVC, but they can just as well be helpful methods which can be called by actions. When your application receives a request, the routing will determine which controller and action to run. Then an instance of that controller will be created and the method corresponding to the action (the method with the same name as the action) gets run.
[source, ruby]
----------------------------------------------
......
== Parameter filtering ==
Rails keeps a log file for each environment (development, test and production) in the "log" folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The "filter_parameter_logging":http://api.rubyonrails.org/classes/ActionController/Base.html#M000837 can be used to filter out sensitive information from the log. It works by replacing certain keys in the `params` hash with "[FILTERED]" before they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":
Rails keeps a log file for each environment (development, test and production) in the "log" folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The link:http://api.rubyonrails.org/classes/ActionController/Base.html#M000837[filter_parameter_logging] method can be used to filter out sensitive information from the log. It works by replacing certain keys in the `params` hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":
[source, ruby]
-------------------------
......
......@@ -8,7 +8,7 @@ class ClientsController < ActionController::Base
# This action uses query string parameters because it gets run by a HTTP GET request,
# but this does not make any difference to the way in which the parameters are accessed.
# The URL for this action would look like this in order to list activated clients: /clients/?status=activated
# The URL for this action would look like this in order to list activated clients: /clients?status=activated
def index
if params[:status] = "activated"
@clients = Client.activated
......@@ -47,7 +47,7 @@ The value of `params[:ids]` will now be `["1", "2", "3"]`. Note that parameter v
To send a hash you include the key name inside the brackets:
-------------------------------------
<form action="/clients">
<form action="/clients" method="post">
<input type="text" name="client[name]" value="Acme" />
<input type="text" name="client[phone]" value="12345" />
<input type="text" name="client[address][postcode]" value="12345" />
......
== The request and response objects ==
In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The `request` method contains an instance of "AbstractRequest":http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html and the `response` method contains the "response object":http://github.com/rails/rails/tree/master/actionpack/lib/action_controller/response.rb representing what is going to be sent back to the client.
In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The `request` method contains an instance of link:http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html[AbstractRequest] and the `response` method contains the link:http://github.com/rails/rails/tree/master/actionpack/lib/action_controller/response.rb[response object] representing what is going to be sent back to the client.
=== The request ===
The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the "Rails API documentation":http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html
The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the link:http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html[API documentation].
* host - The hostname used for this request.
* domain - The hostname without the first part (usually "www").
......
== Rescue ==
Describe how to use rescue_from et al to rescue exceptions in controllers.
Most likely your application is going to contain bugs or otherwise throw an exception that needs to be handled. For example, if the user follows a link to a resource that no longer exists in the database, Active Record will throw the ActiveRecord::RecordNotFound exception. Rails' default exception handling displays a 500 Server Error message for all exceptions. If the request was made locally, a nice traceback and some added information gets displayed so you can figure out what went wrong and deal with it. If the request was remote Rails will just display a simple "500 Server Error" message to the user, or a "404 Not Found" if there was a routing error or a record could not be found. Sometimes you might want to customize how these errors are caught and how they're displayed to the user. There are several levels of exception handling available in a Rails application:
=== The default 500 and 404 templates ===
By default a production application will render either a 404 or a 500 error message. These messages are contained in static HTML files in the `public` folder, in `404.html` and `500.html` respectively. You can customize these files to add some extra information and layout, but remember that they are static; i.e. you can't use RHTML or layouts in them, just plain HTML.
=== `rescue_from` ===
If you want to do something a bit more elaborate when catching errors, you can use link::http://api.rubyonrails.org/classes/ActionController/Rescue/ClassMethods.html#M000620[rescue_from], which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses. When an exception occurs which is caught by a rescue_from directive, the exception object is passed to the handler. The handler can be a method or a Proc object passed to the `:with` option. You can also use a block directly instead of an explicit Proc object.
Let's see how we can use rescue_from to intercept all ActiveRecord::RecordNotFound errors and do something with them.
[source, ruby]
-----------------------------------
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found
private
def record_not_found
render :text => "404 Not Found", :status => 404
end
end
-----------------------------------
Of course, this example is anything but elaborate and doesn't improve the default exception handling at all, but once you can catch all those exceptions you're free to do whatever you want with them. For example, you could create custom exception classes that will be thrown when a user doesn't have access to a certain section of your application:
[source, ruby]
-----------------------------------
class ApplicationController < ActionController::Base
rescue_from User::NotAuthorized, :with => :user_not_authorized
private
def user_not_authorized
flash[:error] = "You don't have access to this section."
redirect_to :back
end
end
class ClientsController < ApplicationController
# Check that the user has the right authorization to access clients.
before_filter :check_authorization
# Note how the actions don't have to worry about all the auth stuff.
def edit
@client = Client.find(params[:id])
end
private
# If the user is not authorized, just throw the exception.
def check_authorization
raise User::NotAuthorized unless current_user.admin?
end
end
-----------------------------------
NOTE: Certain exceptions are only rescuable from the ApplicationController class, as they are raised before the controller gets initialized and the action gets executed. See Pratik Naik's link:http://m.onkey.org/2008/7/20/rescue-from-dispatching[article] on the subject for more information.
== Session ==
Your application sets up a session for each user which can persist small amounts of data between requests. The session is only available in the controller. It can be stored in a number of different session stores:
TODO: Not sure if all of these are available by default.
Your application has a session for each user in which you can store small amounts of data that will be persisted between requests. The session is only available in the controller and can use one of a number of different storage mechanisms:
* CookieStore - Stores everything on the client.
* SQLSessionStore - Stores the data in a database using SQL.
* DRBStore - Stores the data on a DRb client.
* MemCacheStore - Stores the data in MemCache.
* ActiveRecordStore - Stores the data in a database using Active Record.
All session stores store the session id in a cookie - there is no other way of passing it to the server. Most stores also use this key to locate the session data on the server.
The default and recommended store, the Cookie Store, does not store session data on the server, but in the cookie itself. The data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents. It can only store 4Kb of data - much less than the others - but this is usually enough. Storing large amounts of data is discouraged no matter which session store your application uses. Expecially discouraged is storing complex objects (anything other than basic Ruby objects) in the session, as the server might not be able to reassemble them between requests, which will result in an error. The Cookie Store has the added advantage that it does not require any setting up beforehand - Rails will generate a "secret key" which will be used to sign the cookie when you create the application.
The default and recommended store, the Cookie Store, does not store session data on the server, but in the cookie itself. The data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents. It can only store about 4kB of data - much less than the others - but this is usually enough. Storing large amounts of data is discouraged no matter which session store your application uses. Expecially discouraged is storing complex objects (anything other than basic Ruby objects, the primary example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error. The Cookie Store has the added advantage that it does not require any setting up beforehand - Rails will generate a "secret key" which will be used to sign the cookie when you create the application.
If you need a different session storage mechanism, you can change it in the `config/environment.rb` file:
[source, ruby]
------------------------------------------
# Set to one of [:active_record_store, :sql_session_store, :drb_store, :mem_cache_store, :cookie_store]
# Set to one of [:active_record_store, :drb_store, :mem_cache_store, :cookie_store]
config.action_controller.session_store = :active_record_store
------------------------------------------
=== Disabling the session ===
Sometimes you don't need a session, and you can turn it off to avoid the unnecessary overhead. To do this, use the link:http://api.rubyonrails.org/classes/ActionController/SessionManagement/ClassMethods.html#M000649[session] class method in your controller:
[source, ruby]
------------------------------------------
class ApplicationController < ActionController::Base
session :off
end
------------------------------------------
You can also turn the session on or off for a single controller:
[source, ruby]
------------------------------------------
# The session is turned off by default in ApplicationController, but we
# want to turn it on for log in/out.
class LoginsController < ActionController::Base
session :on
end
------------------------------------------
Or even a single action:
[source, ruby]
------------------------------------------
class ProductsController < ActionController::Base
session :on, :only => [:create, :update]
end
------------------------------------------
=== Accessing the session ===
In your controller you can access the session through the `session` method. Session values are stored using key/value pairs like a hash:
In your controller you can access the session through the `session` instance method.
NOTE: There are two `session` methods, the class and the instance method. The class method which is described above is used to turn the session on and off while the instance method described below is used to access session values. The class method is used outside of method definitions while the instance methods is used inside methods, in actions or filters.
Session values are stored using key/value pairs like a hash:
[source, ruby]
------------------------------------------
......@@ -33,6 +65,8 @@ class ApplicationController < ActionController::Base
private
# Finds the User with the ID stored in the session with the key :current_user_id
# This is a common way to do user login in a Rails application; logging in sets the
# session value and logging out removes it.
def current_user
@_current_user ||= session[:current_user_id] && User.find(session[:current_user_id])
end
......@@ -74,7 +108,7 @@ class LoginsController < ApplicationController
end
------------------------------------------
To reset the entire session, use `reset_session`.
To reset the entire session, use link:http://api.rubyonrails.org/classes/ActionController/Base.html#M000855[reset_session].
=== The flash ===
......@@ -95,18 +129,18 @@ end
The `destroy` action redirects to the application's `root_url`, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to a display eventual errors or notices from the flash in the application's layout:
[source, ruby]
------------------------------------------
<!-- head, etc -->
<body>
<% if flash[:notice] -%>
<p class="notice"><%= flash[:notice] %></p>
<% end -%>
<% if flash[:error] -%>
<p class="error"><%= flash[:error] %></p>
<% end -%>
<!-- more content -->
</body>
<html>
<!-- <head/> -->
<body>
<% if flash[:notice] -%>
<p class="notice"><%= flash[:notice] %></p>
<% end -%>
<% if flash[:error] -%>
<p class="error"><%= flash[:error] %></p>
<% end -%>
<!-- more content -->
</body>
</html>
------------------------------------------
......@@ -128,3 +162,24 @@ class MainController < ApplicationController
end
------------------------------------------
==== flash.now ====
By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the `create` action fails to save a resource and you render the `new` template directly, that's not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use `flash.now` in the same way you use the normal `flash`:
[source, ruby]
------------------------------------------
class ClientsController < ApplicationController
def create
@client = Client.new(params[:client])
if @client.save
# ...
else
flash.now[:error] = "Could not save client"
render :action => "new"
end
end
end
------------------------------------------
== Streaming and file downloads ==
Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the "send_data":http://api.rubyonrails.org/classes/ActionController/Streaming.html#M000624 and the "send_file":http://api.rubyonrails.org/classes/ActionController/Streaming.html#M000623 methods, that will both stream data to the client. `send_file` is a convenience method which lets you provide the name of a file on the disk and it will stream the contents of that file for you.
Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the link:http://api.rubyonrails.org/classes/ActionController/Streaming.html#M000624[send_data] and the link:http://api.rubyonrails.org/classes/ActionController/Streaming.html#M000623[send_file] methods, that will both stream data to the client. `send_file` is a convenience method which lets you provide the name of a file on the disk and it will stream the contents of that file for you.
To stream data to the client, use `send_data`:
......@@ -48,15 +48,15 @@ class ClientsController < ApplicationController
end
----------------------------
NOTE: Be careful when using (or just don't use) "outside" data (params, cookies, etc) to locate the file on disk, as this is a security risk as someone could gain access to files they are not meant to have access to.
This will read and stream the file 4Kb at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the `stream` option or adjust the block size with the `buffer_size` option.
NOTE: It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack.
WARNING: Be careful when using (or just don't use) "outside" data (params, cookies, etc) to locate the file on disk, as this is a security risk as someone could gain access to files they are not meant to have access to.
This will read and stream the file 4Kb at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the `stream` option or adjust the block size with the `buffer_size` option.
TIP: It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack.
=== RESTful downloads ===
While `send_data` works just fine, if you are creating a RESTful application having separate actions for file downloads is a bit ugly. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing "RESTful downloads". Let's try to rewrite the example so that the PDF download is a part of the `show` action:
While `send_data` works just fine, if you are creating a RESTful application having separate actions for file downloads is usually not necessary. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing "RESTful downloads". Let's try to rewrite the example so that the PDF download is a part of the `show` action:
[source, ruby]
----------------------------
......
== Verification ==
Describe how to use the verify methods to make sure some prerequisites are met before an action gets run
Verifications make sure certain criterias are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is present in the `params`, `session` or `flash` hashes or that a certain HTTP method was used or that the request was made using XMLHTTPRequest (Ajax). The default action taken when these criterias are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash messages and HTTP headers to the response. It is described in the link:http://api.rubyonrails.org/classes/ActionController/Verification/ClassMethods.html[API codumentation] as "essentially a special kind of before_filter".
Let's see how we can use verification to make sure the user supplies a username and a password in order to log in:
[source, ruby]
---------------------------------------
class LoginsController < ApplicationController
verify :params => [:username, :password],
:render => {:action => "new"},
:add_flash => {:error => "Username and password required to log in"}
def create
@user = User.authenticate(params[:username], params[:password])
if @user
flash[:notice] = "You're logged in"
redirect_to root_url
else
render :action => "new"
end
end
end
---------------------------------------
Now the `create` action won't run unless the "username" and "password" parameters are present, and if they're not, an error message will be added to the flash and the "new" action will be rendered. But there's something rather important missing from the verification above: It will be used for *every* action in LoginsController, which is not what we want. You can limit which actions it will be used for with the `:only` and `:except` options just like a filter:
[source, ruby]
---------------------------------------
class LoginsController < ApplicationController
verify :params => [:username, :password],
:render => {:action => "new"},
:add_flash => {:error => "Username and password required to log in"},
:only => :create #Only run this verification for the "create" action
end
---------------------------------------
......@@ -427,6 +427,15 @@ If you're loading multiple javascript files, you can create a better user experi
-------------------------------------------------------
<%= javascript_include_tag "main", "columns", :cache => true %>
-------------------------------------------------------
By default, the combined file will be delivered as +javascripts/all.js+. You can specify a location for the cached asset file instead:
[source, ruby]
-------------------------------------------------------
<%= javascript_include_tag "main", "columns", :cache => 'cache/main/display' %>
-------------------------------------------------------
You can even use dynamic paths such as "cache/#{current_site}/main/display"+.
==== Linking to CSS Files with +stylesheet_link_tag+
......@@ -486,6 +495,15 @@ If you're loading multiple CSS files, you can create a better user experience by
<%= stylesheet_link_tag "main", "columns", :cache => true %>
-------------------------------------------------------
By default, the combined file will be delivered as +stylesheets/all.css+. You can specify a location for the cached asset file instead:
[source, ruby]
-------------------------------------------------------
<%= stylesheet_link_tag "main", "columns", :cache => 'cache/main/display' %>
-------------------------------------------------------
You can even use dynamic paths such as "cache/#{current_site}/main/display"+.
==== Linking to Images with +image_tag+
The +image_tag+ helper builds an HTML +<image>+ tag to the specified file. By default, files are loaded from +public/images+. If you don't specify an extension, .png is assumed by default:
......@@ -697,6 +715,7 @@ Rails will render the +_product_ruler+ partial (with no data passed in to it) be
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/15[Lighthouse ticket]
* October 16, 2008: Ready for publication by link:../authors.html#mgunderloy[Mike Gunderloy]
* October 4, 2008: Additional info on partials (+:object+, +:as+, and +:spacer_template+) by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
* September 28, 2008: First draft by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
......
......@@ -354,8 +354,8 @@ In designing a data model, you will sometimes find a model that should have a re
[source, ruby]
-------------------------------------------------------
class Employee < ActiveRecord::Base
has_many :subordinates, :class_name => :user, :foreign_key => "manager_id"
belongs_to :manager, :class_name => :user
has_many :subordinates, :class_name => "User", :foreign_key => "manager_id"
belongs_to :manager, :class_name => "User"
end
-------------------------------------------------------
......@@ -636,12 +636,12 @@ The +belongs_to+ association supports these options:
//
===== +:class_name+
If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if an order belongs to a customer, but the actual name of the model containing customers is patron, you'd set things up this way:
If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if an order belongs to a customer, but the actual name of the model containing customers is +Patron+, you'd set things up this way:
[source, ruby]
-------------------------------------------------------
class Order < ActiveRecord::Base
belongs_to :customer, :class_name => :patron
belongs_to :customer, :class_name => "Patron"
end
-------------------------------------------------------
......@@ -711,7 +711,7 @@ By convention, Rails guesses that the column used to hold the foreign key on thi
[source, ruby]
-------------------------------------------------------
class Order < ActiveRecord::Base
belongs_to :customer, :class_name => :patron, :foreign_key => "patron_id"
belongs_to :customer, :class_name => "Patron", :foreign_key => "patron_id"
end
-------------------------------------------------------
......@@ -863,7 +863,7 @@ In many situations, you can use the default behavior of +has_one+ without any cu
[source, ruby]
-------------------------------------------------------
class Supplier < ActiveRecord::Base
has_one :account, :class_name => :billing, :dependent => :nullify
has_one :account, :class_name => "Billing", :dependent => :nullify
end
-------------------------------------------------------
......@@ -895,12 +895,12 @@ Setting the +:as+ option indicates that this is a polymorphic association. Polym
===== +:class_name+
If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a supplier has an account, but the actual name of the model containing accounts is billing, you'd set things up this way:
If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a supplier has an account, but the actual name of the model containing accounts is Billing, you'd set things up this way:
[source, ruby]
-------------------------------------------------------
class Supplier < ActiveRecord::Base
has_one :account, :class_name => :billing
has_one :account, :class_name => "Billing"
end
-------------------------------------------------------
......@@ -1205,12 +1205,12 @@ Setting the +:as+ option indicates that this is a polymorphic association, as di
===== +:class_name+
If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a customer has many orders, but the actual name of the model containing orders is transactions, you'd set things up this way:
If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a customer has many orders, but the actual name of the model containing orders is +Transaction+, you'd set things up this way:
[source, ruby]
-------------------------------------------------------
class Customer < ActiveRecord::Base
has_many :orders, :class_name => :transaction
has_many :orders, :class_name => "Transaction"
end
-------------------------------------------------------
......@@ -1221,7 +1221,7 @@ The +:conditions+ option lets you specify the conditions that the associated obj
[source, ruby]
-------------------------------------------------------
class Customer < ActiveRecord::Base
has_many :confirmed_orders, :class_name => :orders, :conditions => "confirmed = 1"
has_many :confirmed_orders, :class_name => "Order", :conditions => "confirmed = 1"
end
-------------------------------------------------------
......@@ -1230,7 +1230,7 @@ You can also set conditions via a hash:
[source, ruby]
-------------------------------------------------------
class Customer < ActiveRecord::Base
has_many :confirmed_orders, :class_name => :orders, :conditions => { :confirmed => true }
has_many :confirmed_orders, :class_name => "Order", :conditions => { :confirmed => true }
end
-------------------------------------------------------
......@@ -1321,7 +1321,7 @@ The +:limit+ option lets you restrict the total number of objects that will be f
[source, ruby]
-------------------------------------------------------
class Customer < ActiveRecord::Base
has_many :recent_orders, :class_name => :orders, :order => "order_date DESC", :limit => 100
has_many :recent_orders, :class_name => "Order", :order => "order_date DESC", :limit => 100
end
-------------------------------------------------------
......@@ -1591,19 +1591,19 @@ TIP: The +:foreign_key+ and +:association_foreign_key+ options are useful when s
[source, ruby]
-------------------------------------------------------
class User < ActiveRecord::Base
has_and_belongs_to_many :friends, :class_name => :users,
has_and_belongs_to_many :friends, :class_name => "User",
:foreign_key => "this_user_id", :association_foreign_key => "other_user_id"
end
-------------------------------------------------------
===== +:class_name+
If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a part has many assemblies, but the actual name of the model containing assemblies is gadgets, you'd set things up this way:
If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a part has many assemblies, but the actual name of the model containing assemblies is +Gadget+, you'd set things up this way:
[source, ruby]
-------------------------------------------------------
class Parts < ActiveRecord::Base
has_and_belongs_to_many :assemblies, :class_name => :gadgets
has_and_belongs_to_many :assemblies, :class_name => "Gadget"
end
-------------------------------------------------------
......@@ -1654,7 +1654,7 @@ By convention, Rails guesses that the column in the join table used to hold the
[source, ruby]
-------------------------------------------------------
class User < ActiveRecord::Base
has_and_belongs_to_many :friends, :class_name => :users,
has_and_belongs_to_many :friends, :class_name => "User",
:foreign_key => "this_user_id", :association_foreign_key => "other_user_id"
end
-------------------------------------------------------
......
......@@ -103,6 +103,56 @@ Be aware that `Client.first`/`Client.find(:first)` and `Client.last`/`Client.fin
If you'd like to add conditions to your find, you could just specify them in there, just like `Client.find(:first, :conditions => "orders_count = '2'")`. Now what if that number could vary, say as a parameter from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like `Client.find(:first, :conditions => ["orders_count = ?", params[:orders]])`. ActiveRecord will go through the first element in the conditions value and any additional elements will replace the question marks (?) in the first element. If you want to specify two conditions, you can do it like `Client.find(:first, :conditions => ["orders_count = ? AND locked = ?", params[:orders], false])`. In this example, the first question mark will be replaced with the value in params orders and the second will be replaced with true and this will find the first record in the table that has '2' as its value for the orders_count field and 'false' for its locked field.
The reason for doing code like:
[source, ruby]
`Client.find(:first, :conditions => ["orders_count = ?", params[:orders]])`
instead of:
`Client.find(:first, :conditions => "orders_count = #{params[:orders]}")`
is because of parameter safety. Putting the variable directly into the conditions string will parse the variable *as-is*. This means that it will be an unescaped variable directly from a user who may have malicious intent. If you do this, you put your entire database at risk because once a user finds out he or she can exploit your database they can do just about anything to it. Never ever put your parameters directly inside the conditions string.
If you're looking for a range inside of a table for example users created in a certain timeframe you can use the conditions option coupled with the IN sql statement for this. If we had two dates coming in from a controller we could do something like this to look for a range:
[source, ruby]
Client.find(:all, :conditions => ["created_at IN (?)", (params[:start_date].to_date)..(params[:end_date].to_date)])
This would generate the proper query which is great for small ranges but not so good for larger ranges. For example if you pass in a range of date objects spanning a year that's 365 (or possibly 366, depending on the year) strings it will attempt to match your field against.
[source, sql]
SELECT * FROM `users` WHERE (created_at IN ('2007-12-31','2008-01-01','2008-01-02','2008-01-03','2008-01-04','2008-01-05','2008-01-06','2008-01-07','2008-01-08','2008-01-09','2008-01-10','2008-01-11','2008-01-12','2008-01-13','2008-01-14','2008-01-15','2008-01-16','2008-01-17','2008-01-18','2008-01-19','2008-01-20','2008-01-21','2008-01-22','2008-01-23',...
2008-12-15','2008-12-16','2008-12-17','2008-12-18','2008-12-19','2008-12-20','2008-12-21','2008-12-22','2008-12-23','2008-12-24','2008-12-25','2008-12-26','2008-12-27','2008-12-28','2008-12-29','2008-12-30','2008-12-31'))
Things can get *really* messy if you pass in time objects as it will attempt to compare your field to *every second* in that range:
[source, ruby]
Client.find(:all, :conditions => ["created_at IN (?)", (params[:start_date].to_date.to_time)..(params[:end_date].to_date.to_time)])
[source, sql]
SELECT * FROM `users` WHERE (created_at IN ('2007-12-01 00:00:00', '2007-12-01 00:00:01' ... '2007-12-01 23:59:59', '2007-12-02 00:00:00'))
This could possibly cause your database server to raise an unexpected error, for example MySQL will throw back this error:
[source, txt]
Got a packet bigger than 'max_allowed_packet' bytes: <query>
Where <query> is the actual query used to get that error.
In this example it would be better to use greater-than and less-than operators in SQL, like so:
[source, ruby]
Client.find(:all, :condtions => ["created_at > ? AND created_at < ?", params[:start_date], params[:end_date]])
You can also use the greater-than-or-equal-to and less-than-or-equal-to like this:
[source, ruby]
Client.find(:all, :condtions => ["created_at >= ? AND created_at <= ?", params[:start_date], params[:end_date]])
Just like in Ruby.
== Ordering
If you're getting a set of records and want to force an order, you can use `Client.find(:all, :order => "created_at")` which by default will sort the records by ascending order. If you'd like to order it in descending order, just tell it to do that using `Client.find(:all, :order => "created_at desc")`
......@@ -133,6 +183,8 @@ SELECT * FROM clients LIMIT 5, 5
== Group
TODO
== Read Only
Readonly is a find option that you can set in order to make that instance of the record read-only. Any attempt to alter or destroy the record will not succeed, raising an `ActiveRecord::ReadOnlyRecord` error. To set this option, specify it like this:
......@@ -149,18 +201,26 @@ client.save
== Lock
If you're wanting to stop race conditions for a specific record, say for example you're incrementing a single field for a record you can use the lock option to ensure that the record is updated correctly. It's recommended this be used inside a transaction.
[source, Ruby]
Topic.transaction do
t = Topic.find(params[:id], :lock => true)
t.increment!(:views)
end
== Making It All Work Together
You can chain these options together in no particular order as ActiveRecord will write the correct SQL for you. For example you could do this: `Client.find(:all, :order => "created_at DESC", :select => "viewable_by, created_at", :conditions => ["viewable_by = ?", params[:level]], :limit => 10), which should execute a query like `SELECT viewable_by, created_at FROM clients WHERE ORDER BY created_at DESC LIMIT 0,10` if you really wanted it.
You can chain these options together in no particular order as ActiveRecord will write the correct SQL for you. If you specify two instances of the same options inside the find statement ActiveRecord will use the latter.
== Eager Loading
Eager loading is loading associated records along with any number of records in as few queries as possible. Lets say for example if we wanted to load all the addresses associated with all the clients all in the same query we would use `Client.find(:all, :include => :address)`. If we wanted to include both the address and mailing address for the client we would use `Client.find(:all), :include => [:address, :mailing_address]). Inclue will first find the client records and then load the associated address records. Running script/server in one window, and executing the code through script/console in another window, the output should look similar to this:
[source, sql]
Client Load (0.000383) SELECT \* FROM clients
Address Load (0.119770) SELECT addresses.\* FROM addresses WHERE (addresses.client_id IN (13,14))
MailingAddress Load (0.001985) SELECT mailing_addresses.\* FROM mailing_addresses WHERE (mailing_addresses.client_id IN (13,14))
Client Load (0.000383) SELECT * FROM clients
Address Load (0.119770) SELECT addresses.* FROM addresses WHERE (addresses.client_id IN (13,14))
MailingAddress Load (0.001985) SELECT mailing_addresses.* FROM mailing_addresses WHERE (mailing_addresses.client_id IN (13,14))
The numbers `13` and `14` in the above SQL are the ids of the clients gathered from the `Client.find(:all)` query. Rails will then run a query to gather all the addresses and mailing addresses that have a client_id of 13 or 14. Although this is done in 3 queries, this is more efficient than not eager loading because without eager loading it would run a query for every time you called `address` or `mailing_address` on one of the objects in the clients array, which may lead to performance issues if you're loading a large number of records at once.
......@@ -168,8 +228,17 @@ An alternative (and more efficient) way to do eager loading is to use the joins
[source, sql]
`Client Load (0.000455) SELECT clients.* FROM clients INNER JOIN addresses ON addresses.client_id = client.id INNER JOIN mailing_addresses ON mailing_addresses.client_id = client.id
This query is more efficent, but there's a gotcha. If you have a client who does not have an address or a mailing address they will not be returned in this query at all. If you have any association as an optional association, you may want to use include rather than joins.
When using eager loading you can specify conditions for the columns of the tables inside the eager loading to get back a smaller subset. If, for example, you want to find a client and all their orders within the last two weeks you could use eager loading with conditions for this:
[source, Ruby]
Client.find(:first, :include => "orders", :conditions => ["orders.created_at >= ? AND orders.created_at <= ?", Time.now - 2.weeks, Time.now])
[source]
== Dynamic finders
With every field (also known as an attribute) you define in your table, ActiveRecord provides finder methods for these. If you have a field called `name` on your Client model for example, you get `find_by_name` and `find_all_by_name` for free from ActiveRecord. If you have also have a `locked` field on the client model, you also get `find_by_locked` and `find_all_by_locked`. If you want to find both by name and locked, you can chain these finders together by simply typing and between the fields for example `Client.find_by_name_and_locked('Ryan', true)`. These finders are an excellent alternative to using the conditions option, mainly because it's shorter to type `find_by_name(params[:name])` than it is to type `find(:first, :conditions => ["name = ?", params[:name]])`.
......@@ -189,6 +258,15 @@ client = Client.find_or_initialize_by_name('Ryan')
will either assign an existing client object with the name 'Ryan' to the client local variable, or initialize new object similar to calling `Client.new(:name => 'Ryan')`. From here, you can modify other fields in client by calling the attribute setters on it: `client.locked = true` and when you want to write it to the database just call `save` on it.
== Finding By SQL
If you'd like to use your own SQL to find records a table you can use `find_by_sql`. `find_by_sql` will return an array of objects even if it only returns a single record in it's call to the database. For example you could run this query:
[source, ruby]
Client.find_by_sql("SELECT * FROM clients INNER JOIN orders ON clients.id = orders.client_id ORDER clients.created_at desc")
`find_by_sql` provides you with a simple way of making custom calls to the database and converting those to objects.
== Working with Associations
When you define a has_many association on a model you get the find method and dynamic finders also on that association. This is helpful for finding associated records within the scope of an exisiting record, for example finding all the orders for a client that have been sent and not received by doing something like `Client.find(params[:id]).orders.find_by_sent_and_received(true, false)`. Having this find method available on associations is extremely helpful when using nested controllers.
......@@ -237,6 +315,45 @@ end
This will work with `Client.recent(2.weeks.ago)` and `Client.recent` with the latter always returning records with a created_at date between right now and 2 weeks ago.
Remember that named scopes are stackable, so you will be able to do `Client.recent(2.weeks.ago).unlocked` to find all clients created between right now and 2 weeks ago and have their locked field set to false.
== Existance of Objects
If you simply want to check for the existance of the object there's a method called `exists?`. This method will query the database using the same query as find, but instead of returning an object or collection of objects it will return either true or false.
[source, ruby]
Client.exists?(1)
The above code will check for the existance of a clients table record with the id of 1 and return true if it exists.
[source, ruby]
Client.exists?(1,2,3)
# or
Client.exists?([1,2,3])
`exists?` also takes multiple ids, as shown by the above code, but the catch is that it will return true if any one of those records exists.
Further more, `exists` takes a `conditions` option much like find:
[source, ruby]
Client.exists?(:conditions => "first_name = 'Ryan'")
== Calculations
=== Count
If you want to see how many records are in your models table you could call `Client.count` and that will return the number. If you want to be more specific and find all the clients with their age present in the database you can use `Client.count(:age)`.
`count` takes conditions much in the same way `exists?` does:
[source, ruby]
Client.count(:conditions => "first_name = 'Ryan'")
[source, sql]
SELECT count(*) AS count_all FROM `clients` WHERE (first_name = 1)
== With Scope
TODO
== Credits
......@@ -258,3 +375,15 @@ Thanks to Mike Gunderloy for his tips on creating this guide.
1. Did section on limit and offset, as well as section on readonly.
2. Altered formatting so it doesn't look bad.
=== Sunday, 05 October 2008
1. Extended conditions section to include IN and using operators inside the conditions.
2. Extended conditions section to include paragraph and example of parameter safety.
3. Added TODO sections.
=== Monday, 06 October 2008
1. Added section in Eager Loading about using conditions on tables that are not the model's own.
=== Thursday, 09 October 2008
1. Wrote section about lock option and tidied up "Making it all work together" section.
2. Added section on using count.
......@@ -43,8 +43,6 @@ This guide covers the find method defined in ActiveRecord::Base, as well as name
.link:actionview/layouts_and_rendering.html[Layouts and Rendering in Rails]
***********************************************************
CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/15[Lighthouse Ticket]
This guide covers the basic layout features of Action Controller and Action View,
including rendering and redirecting, using +content_for_ blocks, and working
with partials.
......
......@@ -267,10 +267,28 @@ Rails allows you to group your controllers into namespaces by saving them in fol
map.resources :adminphotos, :controller => "admin/photos"
-------------------------------------------------------
If you use controller namespaces, you need to be aware of a subtlety in the Rails routing code: it always tries to preserve as much of the namespace from the previous request as possible. For example, if you are on a view generated from the +adminphoto_path+ helper, and you follow a link generated with +<%= link_to "show", adminphoto(1) %> you will end up on the view generated by +admin/photos/show+ but you will also end up in the same place if you have +<%= link_to "show", {:controller => "photos", :action => "show"} %>+ because Rails will generate the show URL relative to the current URL.
If you use controller namespaces, you need to be aware of a subtlety in the Rails routing code: it always tries to preserve as much of the namespace from the previous request as possible. For example, if you are on a view generated from the +adminphoto_path+ helper, and you follow a link generated with +<%= link_to "show", adminphoto(1) %>+ you will end up on the view generated by +admin/photos/show+ but you will also end up in the same place if you have +<%= link_to "show", {:controller => "photos", :action => "show"} %>+ because Rails will generate the show URL relative to the current URL.
TIP: If you want to guarantee that a link goes to a top-level controller, use a preceding slash to anchor the controller name: +<%= link_to "show", {:controller => "/photos", :action => "show"} %>+
You can also specify a controller namespace with the +:namespace+ option instead of a path:
[source, ruby]
-------------------------------------------------------
map.resources :adminphotos, :namespace => "admin", :controller => "photos"
-------------------------------------------------------
This can be especially useful when combined with +with_options+ to map multiple namespaced routes together:
[source, ruby]
-------------------------------------------------------
map.with_options(:namespace => "admin") do |admin|
admin.resources :photos, :videos
end
-------------------------------------------------------
That would give you routing for +admin/photos+ and +admin/videos+ controllers.
==== Using :singular
If for some reason Rails isn't doing what you want in converting the plural resource name to a singular name in member routes, you can override its judgment with the +:singular+ option:
......@@ -366,6 +384,8 @@ Routes recognized by this entry would include:
NOTE: In most cases, it's simpler to recognize URLs of this sort by creating nested resources, as discussed in the next section.
NOTE: You can also use +:path_prefix+ with non-RESTful routes.
==== Using :name_prefix
You can use the :name_prefix option to avoid collisions between routes. This is most useful when you have two resources with the same name that use +:path_prefix+ to map differently. For example:
......@@ -378,6 +398,8 @@ map.resources :photos, :path_prefix => '/agencies/:agency_id', :name_prefix => '
This combination will give you route helpers such as +photographer_photos_path+ and +agency_edit_photo_path+ to use in your code.
NOTE: You can also use +:name_prefix+ with non-RESTful routes.
=== Nested Resources
It's common to have resources that are logically children of other resources. For example, suppose your application includes these models:
......@@ -417,7 +439,7 @@ PUT /magazines/1/ads/1 Ads update update a specific ad be
DELETE /magazines/1/ads/1 Ads destroy delete a specific ad belonging to a specific magazine
--------------------------------------------------------------------------------------------
This will also create routing helpers such as +magazine_ads_url+ and +magazine_edit_ad_path+.
This will also create routing helpers such as +magazine_ads_url+ and +edit_magazine_ad_path+.
==== Using :name_prefix
......
......@@ -79,7 +79,7 @@ This will also be a good idea, if you modify the structure of an object and old
-- _Rails provides several storage mechanisms for the session hashes, the most important are ActiveRecordStore and CookieStore._
There are a number of session storages, i.e. where Rails saves the session hash and session id. Mot real-live applications choose ActiveRecordStore (or one of its derivatives) over file storage due to performance and maintenance reasons. ActiveRecordStore keeps the session id and hash in a database table and saves and retrieves the hash on every request.
There are a number of session storages, i.e. where Rails saves the session hash and session id. Most real-live applications choose ActiveRecordStore (or one of its derivatives) over file storage due to performance and maintenance reasons. ActiveRecordStore keeps the session id and hash in a database table and saves and retrieves the hash on every request.
Rails 2 introduced a new default session storage, CookieStore. CookieStore saves the session hash directly in a cookie on the client-side. The server retrieves the session hash from the cookie and eliminates the need for a session id. That will greatly increase the speed of the application, but it is a controversial storage option and you have to think about the security implications of it:
......@@ -507,7 +507,7 @@ It is interesting that only 4% of these passwords were dictionary words and the
A good password is a long alphanumeric combination of mixed cases. As this is quite hard to remember, it is advisable to enter only the [,#fffcdb]#first letters of a sentence that you can easily remember#. For example "The quick brown fox jumps over the lazy dog" will be "Tqbfjotld". Note that this is just an example, you should not use well known phrases like these, as they might appear in cracker dictionaries, too.
=== Regular expressions
-- _A common pitfall in Ruby's regular expressions is to match the string's end and beginning by $ and ^, instead of \z and \A._
-- _A common pitfall in Ruby's regular expressions is to match the string's beginning and end by ^ and $, instead of \A and \z._
Ruby uses a slightly different approach to match the end and the beginning of a string. That is why even many Ruby and Rails books make this wrong. So how is this a security threat? Imagine you have a File model and you validate the file name by a regular expression like this:
......@@ -523,7 +523,7 @@ This means, upon saving, the model will validate the file name to consist only o
file.txt%0A<script>alert('hello')</script>
..........
Whereas %0A is a line feed and %0D is a carriage return, in URL encoding. This file name passes the filter because the regular expression matches – up to the line end, the rest does not matter. The correct expression should read:
Whereas %0A is a line feed in URL encoding, so Rails automatically converts it to "file.txt\n<script>alert('hello')</script>". This file name passes the filter because the regular expression matches – up to the line end, the rest does not matter. The correct expression should read:
..........
/\A[\w\.\-\+]+\z/
......@@ -859,4 +859,4 @@ The security landscape shifts and it is important to keep up to date, because mi
- Subscribe to the Rails security http://groups.google.com/group/rubyonrails-security[mailing list]
- http://secunia.com/[Keep up to date on the other application layers] (they have a weekly newsletter, too)
- A http://ha.ckers.org/blog/[good security blog] including the http://ha.ckers.org/xss.html[Cross-Site scripting Cheat Sheet]
- Another http://www.0x000000.com/[good security blog] with some Cheat Sheets, too
\ No newline at end of file
- Another http://www.0x000000.com/[good security blog] with some Cheat Sheets, too
......@@ -22,8 +22,10 @@
# Specify gems that this application depends on.
# They can then be installed with "rake gems:install" on new installations.
# You have to specify the <tt>:lib</tt> option for libraries, where the Gem name (<em>sqlite3-ruby</em>) differs from the file itself (_sqlite3_)
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
# Only load the plugins named here, in the order given. By default, all plugins
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册