diff --git a/railties/doc/guides/html/activerecord_validations_callbacks.html b/railties/doc/guides/html/activerecord_validations_callbacks.html index 0862776f53..5251869119 100644 --- a/railties/doc/guides/html/activerecord_validations_callbacks.html +++ b/railties/doc/guides/html/activerecord_validations_callbacks.html @@ -645,7 +645,7 @@ http://www.gnu.org/software/src-highlite -->
The default error message for validates_presence_of is "can’t be empty".
ActiveRecord::Base has methods defined on it to make interacting with your database and the tables within it much, much easier. For finding records, the key method is find. This method allows you to pass arguments into it to perform certain queries on your database without the need of SQL. If you wanted to find the record with the id of 1, you could type Client.find(1) which would execute this query on your database:
You may see in Rails code that there are calls to methods such as Client.find(:all), Client.find(:first) and Client.find(:last). These methods are just alternatives to Client.all, Client.first and Client.last respectively.
Be aware that Client.first/Client.find(:first) and Client.last/Client.find(:last) will both return a single object, where as Client.all/Client.find(:all) will return an array of Client objects, just as passing in an array of ids to find will do also.
The find method allows you to specify conditions to limit the records returned. You can specify conditions as a string, array, or hash.
If you’d like to add conditions to your find, you could just specify them in there, just like Client.first(:conditions => "orders_count = 2"). This will find all clients where the orders_count field’s value is 2.
| Building your own conditions as pure strings can leave you vulnerable to SQL injection exploits. For example, Client.first(:conditions => "name LIKE %#{params[:name]}%") is not safe. See the next section for the preferred way to handle conditions using an array. |
Now what if that number could vary, say as a argument from somewhere, or perhaps from the user’s level status somewhere? The find then becomes something like Client.first(:conditions => ["orders_count = ?", params[:orders]]). Active Record 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.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 the SQL representation of false, which depends on the adapter.
The reason for doing code like:
Client.all(:conditions => ["created_at >= ? AND created_at <= ?", params[:start_date], params[:end_date]])
Just like in Ruby. If you want a shorter syntax be sure to check out the Hash Conditions section later on in the guide.
Similar to the array style of params you can also specify keys in your conditions:
Client.all(:conditions => ["created_at >= :start_date AND created_at <= :end_date", { :start_date => params[:start_date], :end_date => params[:end_date] }])
This makes for clearer readability if you have a large number of variable conditions.
Rails also allows you to pass in a hash conditions which can increase the readability of your conditions syntax. With hash conditions, you pass in a hash with keys of the fields you want conditionalised and the values of how you want to conditionalise them:
SELECT * FROM `clients` WHERE (`clients`.`orders_count` IN (1,2,3))
If you’re getting a set of records and want to order them in ascending order by the created_at field in your table, you can use Client.all(:order => "created_at"). If you’d like to order it in descending order, just tell it to do that using Client.all(:order => "created_at desc"). The value for this option is passed in as sanitized SQL and allows you to sort via multiple fields: Client.all(:order => "created_at desc, orders_count asc").
To select certain fields, you can use the select option like this: Client.first(:select => "viewable_by, locked"). This select option does not use an array of fields, but rather requires you to type SQL-like code. The above code will execute SELECT viewable_by, locked FROM clients LIMIT 1 on your database.
Be careful because this also means you’re initializing a model object with only the fields that you’ve selected. If you attempt to access a field that is not in the initialized record you’ll receive:
Where <attribute> is the atrribute you asked for. The id method will not raise the ActiveRecord::MissingAttributeError, so just be careful when working with associations because they need the id method to function properly.
You can also call SQL functions within the select option. For example, if you would like to only grab a single record per unique value in a certain field by using the DISTINCT function you can do it like this: Client.all(:select => "DISTINCT(name)").
If you want to limit the amount of records to a certain subset of all the records retrieved you usually use limit for this, sometimes coupled with offset. Limit is the maximum number of records that will be retrieved from a query, and offset is the number of records it will start reading from from the first record of the set. Take this code for example:
SELECT * FROM clients LIMIT 5, 5
The group option for find is useful, for example, if you want to find a collection of the dates orders were created on. You could use the option in this context:
SELECT * FROM orders GROUP BY date(created_at)
The :having option allows you to specify SQL and acts as a kind of a filter on the group option. :having can only be specified when :group is specified.
An example of using it would be:
Order.all(:group => "date(created_at)", :having => ["created_at > ?", 1.month.ago])
This will return single order objects for each day, but only for the last month.
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 exception. To set this option, specify it like this:
If you’re wanting to stop race conditions for a specific record (for example, you’re incrementing a single field for a record, potentially from multiple simultaneous connections) you can use the lock option to ensure that the record is updated correctly. For safety, you should use this inside a transaction.
You can chain these options together in no particular order as Active Record will write the correct SQL for you. If you specify two instances of the same options inside the find method Active Record will use the last one you specified. This is because the options passed to find are a hash and defining the same key twice in a hash will result in the last definition being used.
Eager loading is loading associated records along with any number of records in as few queries as possible. For example, if you wanted to load all the addresses associated with all the clients in a single query you could use Client.all(:include => :address). If you wanted to include both the address and mailing address for the client you would use Client.find(:all, :include => [:address, :mailing_address]). Include 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:
Client.first(:include => "orders", :conditions => ["orders.created_at >= ? AND orders.created_at <= ?", 2.weeks.ago, Time.now])
For every field (also known as an attribute) you define in your table, Active Record provides a finder method. 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 Active Record. If you have also have a locked field on the Client model, you also get find_by_locked and find_all_by_locked.
You can do find_last_by_* methods too which will find the last record matching your argument.
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 a 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.
If you’d like to use your own SQL to find records in a table you can use find_by_sql. The find_by_sql method will return an array of objects even the underlying query returns just a single record. For example you could run this query:
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 retrieving instantiated objects.
find_by_sql has a close relative called connection#select_all. select_all will retrieve objects from the database using custom SQL just like find_by_sql but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record.
Client.connection.select_all("SELECT * FROM `clients` WHERE `id` = '1'")
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 existing 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 resources.
Named scopes are another way to add custom finding behavior to the models in the application. Named scopes provide an object-oriented way to narrow the results of a query.
Suppose we want to find all clients who are male. You could use this code:
You can call this new named_scope with Client.active.all and this will do the same query as if we just used Client.all(:conditions => ["active = ?", true]). If you want to find the first client within this named scope you could do Client.active.first.
If you wanted to find all the clients who are active and male you can stack the named scopes like this:
Client.males.active.all(:conditions => ["age > ?", params[:age]])
Consider the following code:
And now every time the recent named scope is called, the code in the lambda block will be executed, so you’ll get actually 2 weeks ago from the code execution, not 2 weeks ago from the time the model was loaded.
In a named scope you can use :include and :joins options just like in find.
This method, called as Client.active_within_2_weeks.all, will return all clients who have placed orders in the past 2 weeks.
If you want to pass to a named scope a required arugment, just specify it as a block argument like this:
This will work with Client.recent(2.weeks.ago).all and Client.recent.all, 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.all to find all clients created between right now and 2 weeks ago and have their locked field set to false.
All Active Record models come with a named scope named scoped, which allows you to create anonymous scopes. For example:
Client.scoped(:conditions => { :gender => "male" })
Just like named scopes, anonymous scopes can be stacked, either with other anonymous scopes or with regular named scopes.
If you simply want to check for the existence 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+.
Client.exists?(:conditions => "first_name = 'Ryan'")
This section uses count as an example method in this preamble, but the options described apply to all sub-sections.
count takes conditions much in the same way exists? does:
This code specifies clients.first_name just in case one of the join tables has a field also called first_name and it uses orders.status because that’s the name of our join table.
If you want to see how many records are in your model’s 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).
For options, please see the parent section, Calculations.
If you want to see the average of a certain number in one of your tables you can call the average method on the class that relates to the table. This method call will look something like this:
Client.average("orders_count")
This will return a number (possibly a floating point number such as 3.14159265) representing the average value in the field.
For options, please see the parent section, Calculations.
If you want to find the minimum value of a field in your table you can call the minimum method on the class that relates to the table. This method call will look something like this:
Client.minimum("age")
For options, please see the parent section, Calculations
If you want to find the maximum value of a field in your table you can call the maximum method on the class that relates to the table. This method call will look something like this:
Client.maximum("age")
For options, please see the parent section, Calculations
If you want to find the sum of a field for all records in your table you can call the sum method on the class that relates to the table. This method call will look something like this:
Client.sum("orders_count")
For options, please see the parent section, Calculations
Thanks to Ryan Bates for his awesome screencast on named scope #108. The information within the named scope section is intentionally similar to it, and without the cast may have not been possible.
Thanks to Mike Gunderloy for his tips on creating this guide.
-December 29 2008: Added James B. Byrne’s suggestions from this ticket -
--December 23 2008: Xavier Noria suggestions added! From this ticket and this ticket and this ticket -
--December 22 2008: Added section on having. -
--December 22 2008: Added description of how to make hash conditions use an IN expression mentioned here -
--December 22 2008: Mentioned using SQL as values for the lock option as mentioned in this ticket -
--December 21 2008: Fixed this ticket minus two points; the lock SQL syntax and the having option. -
--December 21 2008: Added more to the has conditions section. -
--December 17 2008: Fixed up syntax errors. -
--December 16 2008: Covered hash conditions that were introduced in Rails 2.2.2. -
--December 1 2008: Added using an SQL function example to Selecting Certain Fields section as per this ticket -
--November 23 2008: Added documentation for find_by_last and find_by_bang! -
--November 21 2008: Fixed all points specified in this comment and this comment -
--November 18 2008: Fixed all points specified in this comment -
--November 8, 2008: Editing pass by Mike Gunderloy . First release version. -
--October 27, 2008: Added scoped section, added named params for conditions and added sub-section headers for conditions section by Ryan Bigg -
--October 27, 2008: Fixed up all points specified in this comment with an exception of the final point by Ryan Bigg -
--October 26, 2008: Editing pass by Mike Gunderloy . First release version. -
--October 22, 2008: Calculations complete, first complete draft by Ryan Bigg -
--October 21, 2008: Extended named scope section by Ryan Bigg -
--October 9, 2008: Lock, count, cleanup by Ryan Bigg -
--October 6, 2008: Eager loading by Ryan Bigg -
--October 5, 2008: Covered conditions by Ryan Bigg -
--October 1, 2008: Covered limit/offset, formatting changes by Ryan Bigg -
--September 28, 2008: Covered first/last/all by Ryan Bigg +December 29 2008: Initial version by Ryan Bigg
Performance tests are run in the development environment. But running performance tests will set the following configuration parameters:
ActionController::Base.perform_caching = true +ActiveSupport::Dependencies.mechanism = :require +Rails.logger.level = ActiveSupport::BufferedLogger::INFO
As ActionController::Base.perform_caching is set to true, performance tests will behave much as they do in the production environment.
To get the best from Rails performance tests, you need to build a special Ruby binary with some super powers - GC patch for measuring GC Runs/Time and memory/object allocation.
The process is fairly straight forward. If you’ve never compiled a Ruby binary before, follow these steps to build a ruby binary inside your home directory:
Compile Ruby and apply this GC Patch:
[lifo@null ruby-version]$ curl http://rubyforge.org/tracker/download.php/1814/7062/17676/3291/ruby186gc.patch | patch -p0
The following will install ruby in your home directory’s /rubygc directory. Make sure to replace <homedir> with a full patch to your actual home directory.
[lifo@null ruby-version]$ ./configure --prefix=/<homedir>/rubygc [lifo@null ruby-version]$ make && make install
For convenience, add the following lines in your ~/.profile:
Download Rubygems and install it from source. Rubygem’s README file should have necessary installation instructions.
Additionally, install the following gems :
This guide covers Rails integration with Rack and interfacing with other Rack components. By referring to this guide, you will be able to:
-Create Rails Metal applications -
--Use Rack Middlewares in your Rails applications -
--Understand Action Pack’s internal Middleware stack -
--Define custom internal Middleware stack -
--Understand the best practices for developing a middleware aimed at Rails applications -
-|
- |
-This guide assumes a working knowledge of Rack protocol and Rack concepts such as middlewares | -
Explaining Rack is not really in the scope of this guide. In case you are not familiar with Rack’s basics, you should check out the following links:
ActionController::Dispatcher.new is the primary Rack application object of a Rails application. It responds to call method with a single env argument and returns a Rack response. Any Rack compliant web server should be using ActionController::Dispatcher.new object to serve a Rails application.
script/server does the basic job of creating a Rack::Builder object and starting the webserver. This is Rails equivalent of Rack’s rackup script.
Here’s how script/server creates an instance of Rack::Builder
app = Rack::Builder.new { - use Rails::Rack::LogTailer unless options[:detach] - use Rails::Rack::Static - use Rails::Rack::Debugger if options[:debugger] - run ActionController::Dispatcher.new -}.to_app
Middlewares used in the code above are most useful in development envrionment. The following table explains their usage:
| Middleware | -Purpose | -
|---|---|
Rails::Rack::LogTailer |
-Appends log file output to console |
-
Rails::Rack::Static |
-Serves static files inside RAILS_ROOT/public directory |
-
Rails::Rack::Debugger |
-Starts Debugger |
-
To use rackup instead of Rails' script/server, you can put the following inside config.ru of your Rails application’s root directory:
# RAILS_ROOT/config.ru -require "config/environment" - -use Rails::Rack::LogTailer -use Rails::Rack::Static -run ActionController::Dispatcher.new
And start the server:
[lifo@null application]$ rackup
To find out more about different rackup options:
[lifo@null application]$ rackup --help
Many of Action Controller’s internal components are implemented as Rack middlewares. ActionController::Dispatcher uses ActionController::MiddlewareStack to combine various internal and external middlewares to form a complete Rails Rack application.
|
- |
-
- What is ActionController::MiddlewareStack ? ActionController::MiddlewareStack is Rails equivalent of Rack::Builder, but built for better flexibility and more features to meet Rails' requirements. |
-
Rails provides a very simple configuration interface for adding generic Rack middlewares to a Rails applications.
Here’s how you can add middlewares via environment.rb
# environment.rb - -config.middleware.use Rack::BounceFavicon
use "ActionController::Lock", :if => lambda { - !ActionController::Base.allow_concurrency -} - -use "ActionController::Failsafe" - -use "ActiveRecord::QueryCache", :if => lambda { defined?(ActiveRecord) } - -["ActionController::Session::CookieStore", - "ActionController::Session::MemCacheStore", - "ActiveRecord::SessionStore"].each do |store| - use(store, ActionController::Base.session_options, - :if => lambda { - if session_store = ActionController::Base.session_store - session_store.name == store - end - } - ) -end - -use ActionController::VerbPiggybacking
| Middleware | -Purpose | -
|---|---|
ActionController::Lock |
-Mutex |
-
ActionController::Failsafe |
-Never fail |
-
ActiveRecord::QueryCache |
-Query caching |
-
ActionController::Session::CookieStore |
-Query caching |
-
ActionController::Session::MemCacheStore |
-Query caching |
-
ActiveRecord::SessionStore |
-Query caching |
-
ActionController::VerbPiggybacking |
-_method hax |
-
VERIFY THIS WORKS. Just a code dump at the moment.
Put the following in an initializer.
ActionController::Dispatcher.middleware = ActionController::MiddlewareStack.new do |m| - m.use ActionController::Lock - m.use ActionController::Failsafe - m.use ActiveRecord::QueryCache - m.use ActionController::Session::CookieStore - m.use ActionController::VerbPiggybacking -end
Rails Metal applications are minimal Rack applications specially designed for integrating with a typical Rails applications. As Rails Metal Applications skip all of the Action Controller stack, serving a request has no overhead from the Rails framework itself. This is especially useful for infrequent cases where the performance of the full stack Rails framework is an issue.
Rails provides a generator called performance_test for creating new performance tests:
script/generate metal poller
This generates poller.rb in the app/metal directory:
# Allow the metal piece to run in isolation -require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails) - -class Poller - def self.call(env) - if env["PATH_INFO"] =~ /^\/poller/ - [200, {"Content-Type" => "text/html"}, ["Hello, World!"]] - else - [404, {"Content-Type" => "text/html"}, ["Not Found"]] - end - end -end
Metal applications are an optimization. You should make sure to understand the related performance implications before using it.
-January 11, 2009: First version by Pratik -
-This guide covers Rails integration with Rack and interfacing with other Rack components. By referring to this guide, you will be able to:
+Create Rails Metal applications +
++Use Rack Middlewares in your Rails applications +
++Understand Action Pack’s internal Middleware stack +
++Define custom internal Middleware stack +
++Understand the best practices for developing a middleware aimed at Rails applications +
+|
+ |
+This guide assumes a working knowledge of Rack protocol and Rack concepts such as middlewares, url maps and Rack::Builder. | +
Explaining Rack is not really in the scope of this guide. In case you are not familiar with Rack’s basics, you should check out the following links:
ActionController::Dispatcher.new is the primary Rack application object of a Rails application. It responds to call method with a single env argument and returns a Rack response. Any Rack compliant web server should be using ActionController::Dispatcher.new object to serve a Rails application.
script/server does the basic job of creating a Rack::Builder object and starting the webserver. This is Rails equivalent of Rack’s rackup script.
Here’s how script/server creates an instance of Rack::Builder
app = Rack::Builder.new { + use Rails::Rack::LogTailer unless options[:detach] + use Rails::Rack::Static + use Rails::Rack::Debugger if options[:debugger] + run ActionController::Dispatcher.new +}.to_app
Middlewares used in the code above are most useful in development envrionment. The following table explains their usage:
| Middleware | +Purpose | +
|---|---|
Rails::Rack::LogTailer |
+Appends log file output to console |
+
Rails::Rack::Static |
+Serves static files inside RAILS_ROOT/public directory |
+
Rails::Rack::Debugger |
+Starts Debugger |
+
To use rackup instead of Rails' script/server, you can put the following inside config.ru of your Rails application’s root directory:
# RAILS_ROOT/config.ru +require "config/environment" + +use Rails::Rack::LogTailer +use Rails::Rack::Static +run ActionController::Dispatcher.new
And start the server:
[lifo@null application]$ rackup
To find out more about different rackup options:
[lifo@null application]$ rackup --help
Many of Action Controller’s internal components are implemented as Rack middlewares. ActionController::Dispatcher uses ActionController::MiddlewareStack to combine various internal and external middlewares to form a complete Rails Rack application.
|
+ |
+
+ What is ActionController::MiddlewareStack ? ActionController::MiddlewareStack is Rails equivalent of Rack::Builder, but built for better flexibility and more features to meet Rails' requirements. |
+
Rails provides a very simple configuration interface for adding generic Rack middlewares to a Rails applications.
Here’s how you can add middlewares via environment.rb
# environment.rb + +config.middleware.use Rack::BounceFavicon
use "ActionController::Lock", :if => lambda { + !ActionController::Base.allow_concurrency +} + +use "ActionController::Failsafe" + +use "ActiveRecord::QueryCache", :if => lambda { defined?(ActiveRecord) } + +["ActionController::Session::CookieStore", + "ActionController::Session::MemCacheStore", + "ActiveRecord::SessionStore"].each do |store| + use(store, ActionController::Base.session_options, + :if => lambda { + if session_store = ActionController::Base.session_store + session_store.name == store + end + } + ) +end + +use ActionController::VerbPiggybacking
| Middleware | +Purpose | +
|---|---|
ActionController::Lock |
+Mutex |
+
ActionController::Failsafe |
+Never fail |
+
ActiveRecord::QueryCache |
+Query caching |
+
ActionController::Session::CookieStore |
+Query caching |
+
ActionController::Session::MemCacheStore |
+Query caching |
+
ActiveRecord::SessionStore |
+Query caching |
+
ActionController::VerbPiggybacking |
+_method hax |
+
VERIFY THIS WORKS. Just a code dump at the moment.
Put the following in an initializer.
ActionController::Dispatcher.middleware = ActionController::MiddlewareStack.new do |m| + m.use ActionController::Lock + m.use ActionController::Failsafe + m.use ActiveRecord::QueryCache + m.use ActionController::Session::CookieStore + m.use ActionController::VerbPiggybacking +end
Josh says :
Rails has a handy rake task for inspecting the middleware stack in use:
$ rake middleware
For a freshly generated Rails application, this will produce:
use ActionController::Lock +use ActionController::Failsafe +use ActiveRecord::QueryCache +use ActionController::Session::CookieStore, {:secret=>"aa5150a22c1a5f24112260c33ae2131a88d7539117bfdcd5696fb2be385b60c6da9f7d4ed0a67e3b8cc85cc4e653ba0111dd1f3f8999520f049e2262068c16a6", :session_key=>"_edge_session"} +use Rails::Rack::Metal +use ActionController::VerbPiggybacking +run ActionController::Dispatcher.new
This rake task is very useful if the application requires highly customized Rack middleware setup.
Rails Metal applications are minimal Rack applications specially designed for integrating with a typical Rails application. As Rails Metal Applications skip all of the Action Controller stack, serving a request has no overhead from the Rails framework itself. This is especially useful for infrequent cases where the performance of the full stack Rails framework is an issue.
Rails provides a generator called performance_test for creating new performance tests:
script/generate metal poller
This generates poller.rb in the app/metal directory:
# Allow the metal piece to run in isolation +require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails) + +class Poller + def self.call(env) + if env["PATH_INFO"] =~ /^\/poller/ + [200, {"Content-Type" => "text/html"}, ["Hello, World!"]] + else + [404, {"Content-Type" => "text/html"}, ["Not Found"]] + end + end +end
Metal applications are an optimization. You should make sure to understand the related performance implications before using it.
+January 11, 2009: First version by Pratik +
+assert_select 'title', "Welcome to Rails Testing Guide"-
You can also use nested assert_select blocks. In this case the inner assert_select will run the assertion on each element selected by the outer assert_select block:
You can also use nested assert_select blocks. In this case the inner assert_select runs the assertion on the complete collection of elements selected by the outer assert_select block:
assert_select 'ul.navigation' do assert_select 'li.menu_item' end
The assert_select assertion is quite powerful. For more advanced usage, refer to its documentation.
Alternatively the collection of elements selected by the outer assert_select may be iterated through so that assert_select may be called separately for each element. Suppose for example that the response contains two ordered lists, each with four list elements then the following tests will both pass.
assert_select "ol" do |elements| + elements.each do |element| + assert_select element, "li", 4 + end +end + +assert_select "ol" do + assert_select "li", 8 +end
The assert_select assertion is quite powerful. For more advanced usage, refer to its documentation.
There are more assertions that are primarily used in testing views: