Merge docrails

This commit is contained in:
Pratik Naik 2008-12-19 14:27:43 +00:00
parent 89b7581404
commit c3f53f412c
24 changed files with 898 additions and 1145 deletions

@ -17,6 +17,7 @@ module ActionMailer #:nodoc:
# class Notifier < ActionMailer::Base
# def signup_notification(recipient)
# recipients recipient.email_address_with_name
# bcc ["bcc@example.com", "Order Watcher <watcher@example.com>"]
# from "system@example.com"
# subject "New account information"
# body :account => recipient

@ -111,7 +111,7 @@ def time_ago_in_words(from_time, include_seconds = false)
#
# ==== Options
# * <tt>:use_month_numbers</tt> - Set to true if you want to use month numbers rather than month names (e.g.
# "2" instead of "February").
# "2" instead of "February").
# * <tt>:use_short_month</tt> - Set to true if you want to use the abbreviated month name instead of the full
# name (e.g. "Feb" instead of "February").
# * <tt>:add_month_number</tt> - Set to true if you want to show both, the month's number and name (e.g.

@ -201,13 +201,21 @@ def options_for_select(container, selected = nil)
# Returns a string of option tags that have been compiled by iterating over the +collection+ and assigning the
# the result of a call to the +value_method+ as the option value and the +text_method+ as the option text.
# Example:
# options_from_collection_for_select(@people, 'id', 'name')
# This will output the same HTML as if you did this:
# <option value="#{person.id}">#{person.name}</option>
#
# This is more often than not used inside a #select_tag like this example:
# select_tag 'person', options_from_collection_for_select(@people, 'id', 'name')
#
# If +selected+ is specified, the element returning a match on +value_method+ will get the selected option tag.
#
# Example (call, result). Imagine a loop iterating over each +person+ in <tt>@project.people</tt> to generate an input tag:
# options_from_collection_for_select(@project.people, "id", "name")
# <option value="#{person.id}">#{person.name}</option>
#
# NOTE: Only the option tags are returned, you have to wrap this call in a regular HTML select tag.
# Be sure to specify the same class as the +value_method+ when specifying a selected option.
# Failure to do this will produce undesired results. Example:
# options_from_collection_for_select(@people, 'id', 'name', '1')
# Will not select a person with the id of 1 because 1 (an Integer) is not the same as '1' (a string)
# options_from_collection_for_select(@people, 'id', 'name', 1)
# should produce the desired results.
def options_from_collection_for_select(collection, value_method, text_method, selected = nil)
options = collection.map do |element|
[element.send(text_method), element.send(value_method)]

@ -153,7 +153,7 @@ def clear_association_cache #:nodoc:
# #others.destroy_all | X | X | X
# #others.find(*args) | X | X | X
# #others.find_first | X | |
# #others.exist? | X | X | X
# #others.exists? | X | X | X
# #others.uniq | X | X | X
# #others.reset | X | X | X
#
@ -652,7 +652,7 @@ module ClassMethods
# Returns the number of associated objects.
# [collection.find(...)]
# Finds an associated object according to the same rules as ActiveRecord::Base.find.
# [collection.exist?(...)]
# [collection.exists?(...)]
# Checks whether an associated object with the given conditions exists.
# Uses the same rules as ActiveRecord::Base.exists?.
# [collection.build(attributes = {}, ...)]
@ -682,7 +682,7 @@ module ClassMethods
# * <tt>Firm#clients.empty?</tt> (similar to <tt>firm.clients.size == 0</tt>)
# * <tt>Firm#clients.size</tt> (similar to <tt>Client.count "firm_id = #{id}"</tt>)
# * <tt>Firm#clients.find</tt> (similar to <tt>Client.find(id, :conditions => "firm_id = #{id}")</tt>)
# * <tt>Firm#clients.exist?(:name => 'ACME')</tt> (similar to <tt>Client.exist?(:name => 'ACME', :firm_id => firm.id)</tt>)
# * <tt>Firm#clients.exists?(:name => 'ACME')</tt> (similar to <tt>Client.exists?(:name => 'ACME', :firm_id => firm.id)</tt>)
# * <tt>Firm#clients.build</tt> (similar to <tt>Client.new("firm_id" => id)</tt>)
# * <tt>Firm#clients.create</tt> (similar to <tt>c = Client.new("firm_id" => id); c.save; c</tt>)
# The declaration can also include an options hash to specialize the behavior of the association.
@ -1107,7 +1107,7 @@ def belongs_to(association_id, options = {})
# Finds an associated object responding to the +id+ and that
# meets the condition that it has to be associated with this object.
# Uses the same rules as ActiveRecord::Base.find.
# [collection.exist?(...)]
# [collection.exists?(...)]
# Checks whether an associated object with the given conditions exists.
# Uses the same rules as ActiveRecord::Base.exists?.
# [collection.build(attributes = {})]
@ -1133,7 +1133,7 @@ def belongs_to(association_id, options = {})
# * <tt>Developer#projects.empty?</tt>
# * <tt>Developer#projects.size</tt>
# * <tt>Developer#projects.find(id)</tt>
# * <tt>Developer#clients.exist?(...)</tt>
# * <tt>Developer#clients.exists?(...)</tt>
# * <tt>Developer#projects.build</tt> (similar to <tt>Project.new("project_id" => id)</tt>)
# * <tt>Developer#projects.create</tt> (similar to <tt>c = Project.new("project_id" => id); c.save; c</tt>)
# The declaration may include an options hash to specialize the behavior of the association.

@ -811,8 +811,7 @@ def destroy(id)
#
# ==== Parameters
#
# * +updates+ - A string of column and value pairs that will be set on any records that match conditions.
# What goes into the SET clause.
# * +updates+ - A string of column and value pairs that will be set on any records that match conditions. This creates the SET clause of the generated SQL.
# * +conditions+ - An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. See conditions in the intro for more info.
# * +options+ - Additional options are <tt>:limit</tt> and <tt>:order</tt>, see the examples for usage.
#

@ -123,6 +123,7 @@ def retrieve_connection
connection_handler.retrieve_connection(self)
end
# Returns true if +ActiveRecord+ is connected.
def connected?
connection_handler.connected?(self)
end

@ -32,10 +32,12 @@ def initialize(name, default, sql_type = nil, null = true)
@primary = nil
end
# Returns +true+ if the column is either of type string or text.
def text?
type == :string || type == :text
end
# Returns +true+ if the column is either of type integer, float or decimal.
def number?
type == :integer || type == :float || type == :decimal
end
@ -295,7 +297,7 @@ def add_column_options!(sql, options)
# puts t.class # => "ActiveRecord::ConnectionAdapters::TableDefinition"
# end
# end
#
#
# def self.down
# ...
# end

@ -1049,15 +1049,15 @@ def errors
protected
# Overwrite this method for validation checks on all saves and use <tt>Errors.add(field, msg)</tt> for invalid attributes.
def validate #:doc:
def validate
end
# Overwrite this method for validation checks used only on creation.
def validate_on_create #:doc:
def validate_on_create
end
# Overwrite this method for validation checks used only on updates.
def validate_on_update # :doc:
def validate_on_update
end
end
end

@ -231,7 +231,7 @@ ul#navMain {
<li><a href="#_the_tt_validates_length_of_tt_helper">The <tt>validates_length_of</tt> helper</a></li>
<li><a href="#_the_tt_validates_numericallity_of_tt_helper">The <tt>validates_numericallity_of</tt> helper</a></li>
<li><a href="#_the_tt_validates_numericality_of_tt_helper">The <tt>validates_numericality_of</tt> helper</a></li>
<li><a href="#_the_tt_validates_presence_of_tt_helper">The <tt>validates_presence_of</tt> helper</a></li>
@ -338,7 +338,7 @@ Create your own custom validation methods
</li>
<li>
<p>
Work with the error messages generated by the validation proccess
Work with the error messages generated by the validation process
</p>
</li>
<li>
@ -405,7 +405,7 @@ http://www.gnu.org/software/src-highlite -->
&gt;&gt; p.new_record?
=&gt; false</tt></pre>
</div></div>
<div class="para"><p>Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either <tt>save</tt> or <tt>update_attributes</tt>) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.</p></div>
<div class="para"><p>Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either <tt>save</tt> or <tt>update_attributes</tt>) will result in a SQL update operation. Active Record will use these facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
@ -524,7 +524,8 @@ by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> MovieFile <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
validates_exclusion_of <span style="color: #990000">:</span>format<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">in</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #990000">%</span>w<span style="color: #990000">(</span>mov avi<span style="color: #990000">),</span> <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Extension %s is not allowed"</span>
validates_exclusion_of <span style="color: #990000">:</span>format<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">in</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #990000">%</span>w<span style="color: #990000">(</span>mov avi<span style="color: #990000">),</span>
<span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Extension %s is not allowed"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>The <tt>validates_exclusion_of</tt> helper has an option <tt>:in</tt> that receives the set of values that will not be accepted for the validated attributes. The <tt>:in</tt> option has an alias called <tt>:within</tt> that you can use for the same purpose, if you'd like to. In the previous example we used the <tt>:message</tt> option to show how we can personalize it with the current attribute's value, through the <tt>%s</tt> format mask.</p></div>
@ -537,7 +538,8 @@ by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Product <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
validates_format_of <span style="color: #990000">:</span>description<span style="color: #990000">,</span> <span style="color: #990000">:</span>with <span style="color: #990000">=&gt;</span> <span style="color: #FF6600">/^[a-zA-Z]+$/</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Only letters allowed"</span>
validates_format_of <span style="color: #990000">:</span>description<span style="color: #990000">,</span> <span style="color: #990000">:</span>with <span style="color: #990000">=&gt;</span> <span style="color: #FF6600">/^[a-zA-Z]+$/</span><span style="color: #990000">,</span>
<span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Only letters allowed"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>The default error message for <tt>validates_format_of</tt> is "<em>is invalid</em>".</p></div>
@ -549,7 +551,8 @@ by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Coffee <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
validates_inclusion_of <span style="color: #990000">:</span>size<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">in</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #990000">%</span>w<span style="color: #990000">(</span>small medium large<span style="color: #990000">),</span> <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"%s is not a valid size"</span>
validates_inclusion_of <span style="color: #990000">:</span>size<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">in</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #990000">%</span>w<span style="color: #990000">(</span>small medium large<span style="color: #990000">),</span>
<span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"%s is not a valid size"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>The <tt>validates_inclusion_of</tt> helper has an option <tt>:in</tt> that receives the set of values that will be accepted. The <tt>:in</tt> option has an alias called <tt>:within</tt> that you can use for the same purpose, if you'd like to. In the previous example we used the <tt>:message</tt> option to show how we can personalize it with the current attribute's value, through the <tt>%s</tt> format mask.</p></div>
@ -602,7 +605,7 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>This helper has an alias called <tt>validates_size_of</tt>, it's the same helper with a different name. You can use it if you'd like to.</p></div>
<h3 id="_the_tt_validates_numericallity_of_tt_helper">3.9. The <tt>validates_numericallity_of</tt> helper</h3>
<h3 id="_the_tt_validates_numericality_of_tt_helper">3.9. The <tt>validates_numericality_of</tt> helper</h3>
<div class="para"><p>This helper validates that your attributes have only numeric values. By default, it will match an optional sign followed by a integral or floating point number. Using the <tt>:integer_only</tt> option set to true, you can specify that only integral numbers are allowed.</p></div>
<div class="para"><p>If you use <tt>:integer_only</tt> set to <tt>true</tt>, then it will use the <tt><span>/\A[+\-]?\d+\Z/</span></tt> regular expression to validate the attribute's value. Otherwise, it will try to convert the value using <tt>Kernel.Float</tt>.</p></div>
<div class="listingblock">
@ -611,11 +614,11 @@ by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Player <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
validates_numericallity_of <span style="color: #990000">:</span>points
validates_numericallity_of <span style="color: #990000">:</span>games_played<span style="color: #990000">,</span> <span style="color: #990000">:</span>integer_only <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
validates_numericality_of <span style="color: #990000">:</span>points
validates_numericality_of <span style="color: #990000">:</span>games_played<span style="color: #990000">,</span> <span style="color: #990000">:</span>integer_only <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>The default error message for <tt>validates_numericallity_of</tt> is "<em>is not a number</em>".</p></div>
<div class="para"><p>The default error message for <tt>validates_numericality_of</tt> is "<em>is not a number</em>".</p></div>
<h3 id="_the_tt_validates_presence_of_tt_helper">3.10. The <tt>validates_presence_of</tt> helper</h3>
<div class="para"><p>This helper validates that the attributes are not empty. It uses the <tt>blank?</tt> method to check if the value is either <tt>nil</tt> or an empty string (if the string has only spaces, it will still be considered empty).</p></div>
<div class="listingblock">
@ -673,7 +676,8 @@ by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Holiday <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
validates_uniqueness_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>scope <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>year<span style="color: #990000">,</span> <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Should happen once per year"</span>
validates_uniqueness_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>scope <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>year<span style="color: #990000">,</span>
<span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Should happen once per year"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>There is also a <tt>:case_sensitive</tt> option that you can use to define if the uniqueness contraint will be case sensitive or not. This option defaults to true.</p></div>
@ -692,7 +696,7 @@ http://www.gnu.org/software/src-highlite -->
<div class="sectionbody">
<div class="para"><p>There are some common options that all the validation helpers can use. Here they are, except for the <tt>:if</tt> and <tt>:unless</tt> options, which we'll cover right at the next topic.</p></div>
<h3 id="_the_tt_allow_nil_tt_option">4.1. The <tt>:allow_nil</tt> option</h3>
<div class="para"><p>You may use the <tt>:allow_nil</tt> option everytime you just want to trigger a validation if the value being validated is not <tt>nil</tt>. You may be asking yourself if it makes any sense to use <tt>:allow_nil</tt> and <tt>validates_presence_of</tt> together. Well, it does. Remember, validation will be skipped only for <tt>nil</tt> attributes, but empty strings are not considered <tt>nil</tt>.</p></div>
<div class="para"><p>You may use the <tt>:allow_nil</tt> option everytime you want to trigger a validation only if the value being validated is not <tt>nil</tt>. You may be asking yourself if it makes any sense to use <tt>:allow_nil</tt> and <tt>validates_presence_of</tt> together. Well, it does. Remember, validation will be skipped only for <tt>nil</tt> attributes, but empty strings are not considered <tt>nil</tt>.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@ -713,9 +717,14 @@ by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
validates_uniqueness_of <span style="color: #990000">:</span>email<span style="color: #990000">,</span> <span style="color: #990000">:</span>on <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>create <span style="font-style: italic"><span style="color: #9A1900"># =&gt; it will be possible to update email with a duplicated value</span></span>
validates_numericallity_of <span style="color: #990000">:</span>age<span style="color: #990000">,</span> <span style="color: #990000">:</span>on <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>update <span style="font-style: italic"><span style="color: #9A1900"># =&gt; it will be possible to create the record with a 'non-numerical age'</span></span>
validates_presence_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>on <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>save <span style="font-style: italic"><span style="color: #9A1900"># =&gt; that's the default</span></span>
<span style="font-style: italic"><span style="color: #9A1900"># =&gt; it will be possible to update email with a duplicated value</span></span>
validates_uniqueness_of <span style="color: #990000">:</span>email<span style="color: #990000">,</span> <span style="color: #990000">:</span>on <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>create
<span style="font-style: italic"><span style="color: #9A1900"># =&gt; it will be possible to create the record with a 'non-numerical age'</span></span>
validates_numericality_of <span style="color: #990000">:</span>age<span style="color: #990000">,</span> <span style="color: #990000">:</span>on <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>update
<span style="font-style: italic"><span style="color: #9A1900"># =&gt; the default</span></span>
validates_presence_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>on <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>save
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
</div>
@ -756,7 +765,8 @@ by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Account <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
validates_confirmation_of <span style="color: #990000">:</span>password<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">unless</span></span> <span style="color: #990000">=&gt;</span> Proc<span style="color: #990000">.</span>new <span style="color: #FF0000">{</span> <span style="color: #990000">|</span>a<span style="color: #990000">|</span> a<span style="color: #990000">.</span>password<span style="color: #990000">.</span>blank? <span style="color: #FF0000">}</span>
validates_confirmation_of <span style="color: #990000">:</span>password<span style="color: #990000">,</span>
<span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">unless</span></span> <span style="color: #990000">=&gt;</span> Proc<span style="color: #990000">.</span>new <span style="color: #FF0000">{</span> <span style="color: #990000">|</span>a<span style="color: #990000">|</span> a<span style="color: #990000">.</span>password<span style="color: #990000">.</span>blank? <span style="color: #FF0000">}</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
</div>
@ -770,7 +780,8 @@ http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Invoice <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> validate_on_create
errors<span style="color: #990000">.</span>add<span style="color: #990000">(:</span>expiration_date<span style="color: #990000">,</span> <span style="color: #FF0000">"can't be in the past"</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #990000">!</span>expiration_date<span style="color: #990000">.</span>blank? <span style="font-weight: bold"><span style="color: #0000FF">and</span></span> expiration_date <span style="color: #990000">&lt;</span> Date<span style="color: #990000">.</span>today
errors<span style="color: #990000">.</span>add<span style="color: #990000">(:</span>expiration_date<span style="color: #990000">,</span> <span style="color: #FF0000">"can't be in the past"</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">if</span></span>
<span style="color: #990000">!</span>expiration_date<span style="color: #990000">.</span>blank? <span style="font-weight: bold"><span style="color: #0000FF">and</span></span> expiration_date <span style="color: #990000">&lt;</span> Date<span style="color: #990000">.</span>today
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
@ -781,14 +792,17 @@ by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Invoice <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
validate <span style="color: #990000">:</span>expiration_date_cannot_be_in_the_past<span style="color: #990000">,</span> <span style="color: #990000">:</span>discount_cannot_be_more_than_total_value
validate <span style="color: #990000">:</span>expiration_date_cannot_be_in_the_past<span style="color: #990000">,</span>
<span style="color: #990000">:</span>discount_cannot_be_more_than_total_value
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> expiration_date_cannot_be_in_the_past
errors<span style="color: #990000">.</span>add<span style="color: #990000">(:</span>expiration_date<span style="color: #990000">,</span> <span style="color: #FF0000">"can't be in the past"</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #990000">!</span>expiration_date<span style="color: #990000">.</span>blank? <span style="font-weight: bold"><span style="color: #0000FF">and</span></span> expiration_date <span style="color: #990000">&lt;</span> Date<span style="color: #990000">.</span>today
errors<span style="color: #990000">.</span>add<span style="color: #990000">(:</span>expiration_date<span style="color: #990000">,</span> <span style="color: #FF0000">"can't be in the past"</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">if</span></span>
<span style="color: #990000">!</span>expiration_date<span style="color: #990000">.</span>blank? <span style="font-weight: bold"><span style="color: #0000FF">and</span></span> expiration_date <span style="color: #990000">&lt;</span> Date<span style="color: #990000">.</span>today
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> discount_cannot_be_greater_than_total_value
errors<span style="color: #990000">.</span>add<span style="color: #990000">(:</span>discount<span style="color: #990000">,</span> <span style="color: #FF0000">"can't be greater than total value"</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">unless</span></span> discount <span style="color: #990000">&lt;=</span> total_value
errors<span style="color: #990000">.</span>add<span style="color: #990000">(:</span>discount<span style="color: #990000">,</span> <span style="color: #FF0000">"can't be greater than total value"</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">unless</span></span>
discount <span style="color: #990000">&lt;=</span> total_value
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
@ -874,16 +888,18 @@ person<span style="color: #990000">.</span>errors<span style="color: #990000">.<
person <span style="color: #990000">=</span> Person<span style="color: #990000">.</span>new<span style="color: #990000">(:</span>name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"JD"</span><span style="color: #990000">)</span>
person<span style="color: #990000">.</span>valid? <span style="font-style: italic"><span style="color: #9A1900"># =&gt; false</span></span>
person<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>on<span style="color: #990000">(:</span>name<span style="color: #990000">)</span> <span style="font-style: italic"><span style="color: #9A1900"># =&gt; "is too short (minimum is 3 characters)"</span></span>
person<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>on<span style="color: #990000">(:</span>name<span style="color: #990000">)</span>
<span style="font-style: italic"><span style="color: #9A1900"># =&gt; "is too short (minimum is 3 characters)"</span></span>
person <span style="color: #990000">=</span> Person<span style="color: #990000">.</span>new
person<span style="color: #990000">.</span>valid? <span style="font-style: italic"><span style="color: #9A1900"># =&gt; false</span></span>
person<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>on<span style="color: #990000">(:</span>name<span style="color: #990000">)</span> <span style="font-style: italic"><span style="color: #9A1900"># =&gt; ["can't be blank", "is too short (minimum is 3 characters)"]</span></span>
person<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>on<span style="color: #990000">(:</span>name<span style="color: #990000">)</span>
<span style="font-style: italic"><span style="color: #9A1900"># =&gt; ["can't be blank", "is too short (minimum is 3 characters)"]</span></span>
</tt></pre></div></div>
<div class="ilist"><ul>
<li>
<p>
<tt>clear</tt> is used when you intentionally wants to clear all the messages in the <tt>errors</tt> collection.
<tt>clear</tt> is used when you intentionally want to clear all the messages in the <tt>errors</tt> collection. However, calling <tt>errors.clear</tt> upon an invalid object won't make it valid: the <tt>errors</tt> collection will now be empty, but the next time you call <tt>valid?</tt> or any method that tries to save this object to the database, the validations will run. If any of them fails, the <tt>errors</tt> collection will get filled again.
</p>
</li>
</ul></div>
@ -898,10 +914,15 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
person <span style="color: #990000">=</span> Person<span style="color: #990000">.</span>new
puts person<span style="color: #990000">.</span>valid? <span style="font-style: italic"><span style="color: #9A1900"># =&gt; false</span></span>
person<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>on<span style="color: #990000">(:</span>name<span style="color: #990000">)</span> <span style="font-style: italic"><span style="color: #9A1900"># =&gt; ["can't be blank", "is too short (minimum is 3 characters)"]</span></span>
person<span style="color: #990000">.</span>valid? <span style="font-style: italic"><span style="color: #9A1900"># =&gt; false</span></span>
person<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>on<span style="color: #990000">(:</span>name<span style="color: #990000">)</span>
<span style="font-style: italic"><span style="color: #9A1900"># =&gt; ["can't be blank", "is too short (minimum is 3 characters)"]</span></span>
person<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>clear
person<span style="color: #990000">.</span>errors <span style="font-style: italic"><span style="color: #9A1900"># =&gt; nil</span></span>
person<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>empty? <span style="font-style: italic"><span style="color: #9A1900"># =&gt; true</span></span>
p<span style="color: #990000">.</span>save <span style="font-style: italic"><span style="color: #9A1900"># =&gt; false</span></span>
p<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>on<span style="color: #990000">(:</span>name<span style="color: #990000">)</span>
<span style="font-style: italic"><span style="color: #9A1900"># =&gt; ["can't be blank", "is too short (minimum is 3 characters)"]</span></span>
</tt></pre></div></div>
</div>
<h2 id="_callbacks">8. Callbacks</h2>
@ -910,7 +931,7 @@ person<span style="color: #990000">.</span>errors <span style="font-style: itali
<h3 id="_callbacks_registration">8.1. Callbacks registration</h3>
<div class="para"><p>In order to use the available callbacks, you need to registrate them. There are two ways of doing that.</p></div>
<h3 id="_registering_callbacks_by_overriding_the_callback_methods">8.2. Registering callbacks by overriding the callback methods</h3>
<div class="para"><p>You can specify the callback method direcly, by overriding it. Let's see how it works using the <tt>before_validation</tt> callback, which will surprisingly run right before any validation is done.</p></div>
<div class="para"><p>You can specify the callback method directly, by overriding it. Let's see how it works using the <tt>before_validation</tt> callback, which will surprisingly run right before any validation is done.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@ -1094,7 +1115,7 @@ Readability, since your callback declarations will live at the beggining of your
</div>
<h2 id="_halting_execution">10. Halting Execution</h2>
<div class="sectionbody">
<div class="para"><p>As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks and the database operation to be executed. However, if at any moment one of the callback methods returns a boolean <tt>false</tt> (not <tt>nil</tt>) value, this execution chain will be halted and the desired operation will not complete: your model will not get persisted in the database, or your records will not get deleted and so on.</p></div>
<div class="para"><p>As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks and the database operation to be executed. However, if at any moment one of the <tt>before_create</tt>, <tt>before_save</tt>, <tt>before_update</tt> or <tt>before_destroy</tt> callback methods returns a boolean <tt>false</tt> (not <tt>nil</tt>) value, this execution chain will be halted and the desired operation will not complete: your model will not get persisted in the database, or your records will not get deleted and so on.</p></div>
</div>
<h2 id="_callback_classes">11. Callback classes</h2>
<div class="sectionbody">
@ -1174,7 +1195,7 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<h3 id="_registering_observers">12.1. Registering observers</h3>
<div class="para"><p>If you payed attention, you may be wondering where Active Record Observers are referenced in our applications, so they get instantiate and begin to interact with our models. For observers to work we need to register then in our application's <strong>config/environment.rb</strong> file. In this file there is a commented out line where we can define the observers that our application should load at start-up.</p></div>
<div class="para"><p>If you payed attention, you may be wondering where Active Record Observers are referenced in our applications, so they get instantiate and begin to interact with our models. For observers to work we need to register them somewhere. The usual place to do that is in our application's <strong>config/environment.rb</strong> file. In this file there is a commented out line where we can define the observers that our application should load at start-up.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@ -1183,6 +1204,8 @@ http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># Activate observers that should always be running</span></span>
config<span style="color: #990000">.</span>active_record<span style="color: #990000">.</span>observers <span style="color: #990000">=</span> <span style="color: #990000">:</span>registration_observer<span style="color: #990000">,</span> <span style="color: #990000">:</span>auditor
</tt></pre></div></div>
<div class="para"><p>You can uncomment the line with <tt>config.active_record.observers</tt> and change the symbols for the name of the observers that should be registered.</p></div>
<div class="para"><p>It's also possible to register callbacks in any of the files living at <strong>config/environments/</strong>, if you want an observer to work only in a specific environment. There is not a <tt>config.active_record.observers</tt> line at any of those files, but you can simply add it.</p></div>
<h3 id="_where_to_put_the_observers_source_files">12.2. Where to put the observers' source files</h3>
<div class="para"><p>By convention, you should always save your observers' source files inside <strong>app/models</strong>.</p></div>
</div>

@ -609,6 +609,7 @@ http://www.gnu.org/software/src-highlite -->
<h2 id="_selecting_certain_fields">6. Selecting Certain Fields</h2>
<div class="sectionbody">
<div class="para"><p>To select certain fields, you can use the select option like this: <tt>Client.first(:select &#8658; "viewable_by, locked")</tt>. This select option does not use an array of fields, but rather requires you to type SQL-like code. The above code will execute <tt>SELECT viewable_by, locked FROM clients LIMIT 0,1</tt> on your database.</p></div>
<div class="para"><p>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 <tt>DISTINCT</tt> function you can do it like this: <tt>Client.all(:select &#8658; "DISTINCT(name)")</tt>.</p></div>
</div>
<h2 id="_limit_amp_offset">7. Limit &amp; Offset</h2>
<div class="sectionbody">
@ -1051,6 +1052,11 @@ http://www.gnu.org/software/src-highlite -->
<div class="ilist"><ul>
<li>
<p>
December 1 2008: Added using an SQL function example to Selecting Certain Fields section as per <a href="http://rails.lighthouseapp.com/projects/16213/tickets/36-adding-an-example-for-using-distinct-to-ar-finders">this ticket</a>
</p>
</li>
<li>
<p>
November 23 2008: Added documentation for <tt>find_by_last</tt> and <tt>find_by_bang!</tt>
</p>
</li>

@ -1723,7 +1723,7 @@ http://www.gnu.org/software/src-highlite -->
<td class="icon">
<img src="./images/icons/tip.png" alt="Tip" />
</td>
<td class="content">For more information on routing, see the <a href="../routing_outside_in">Rails Routing from the Outside In</a> guide.</td>
<td class="content">For more information on routing, see the <a href="../routing_outside_in.html">Rails Routing from the Outside In</a> guide.</td>
</tr></table>
</div>
<h3 id="_generating_a_controller">8.4. Generating a Controller</h3>

@ -642,7 +642,7 @@ end</tt></pre>
<div class="para"><p>With those declarations, the <tt>inventory</tt> layout would be used only for the <tt>index</tt> method, the <tt>product</tt> layout would be used for everything else except the <tt>rss</tt> method, and the <tt>rss</tt> method will have its layout determined by the automatic layout rules.</p></div>
<h5 id="_layout_inheritance">Layout Inheritance</h5>
<div class="para"><p>Layouts are shared downwards in the hierarchy, and more specific layouts always override more general ones. For example:</p></div>
<div class="para"><p><tt>application.rb</tt>:</p></div>
<div class="para"><p><tt>application_controller.rb</tt>:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini

File diff suppressed because it is too large Load Diff

@ -47,7 +47,7 @@ We can see how it works by looking at the following script/console output:
=> false
------------------------------------------------------------------
Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either +save+ or +update_attributes+) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.
Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either +save+ or +update_attributes+) will result in a SQL update operation. Active Record will use these facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.
CAUTION: There are four methods that when called will trigger validation: +save+, +save!+, +update_attributes+ and +update_attributes!+. There is one method left, which is +update_attribute+. This method will update the value of an attribute without triggering any validation, so be careful when using +update_attribute+, since it can let you save your objects in an invalid state.
@ -155,7 +155,8 @@ This helper validates that the attributes' values are not included in a given se
[source, ruby]
------------------------------------------------------------------
class MovieFile < ActiveRecord::Base
validates_exclusion_of :format, :in => %w(mov avi), :message => "Extension %s is not allowed"
validates_exclusion_of :format, :in => %w(mov avi),
:message => "Extension %s is not allowed"
end
------------------------------------------------------------------
@ -170,7 +171,8 @@ This helper validates the attributes's values by testing if they match a given p
[source, ruby]
------------------------------------------------------------------
class Product < ActiveRecord::Base
validates_format_of :description, :with => /^[a-zA-Z]+$/, :message => "Only letters allowed"
validates_format_of :description, :with => /^[a-zA-Z]+$/,
:message => "Only letters allowed"
end
------------------------------------------------------------------
@ -183,7 +185,8 @@ This helper validates that the attributes' values are included in a given set. I
[source, ruby]
------------------------------------------------------------------
class Coffee < ActiveRecord::Base
validates_inclusion_of :size, :in => %w(small medium large), :message => "%s is not a valid size"
validates_inclusion_of :size, :in => %w(small medium large),
:message => "%s is not a valid size"
end
------------------------------------------------------------------
@ -223,7 +226,7 @@ end
This helper has an alias called +validates_size_of+, it's the same helper with a different name. You can use it if you'd like to.
=== The +validates_numericallity_of+ helper
=== The +validates_numericality_of+ helper
This helper validates that your attributes have only numeric values. By default, it will match an optional sign followed by a integral or floating point number. Using the +:integer_only+ option set to true, you can specify that only integral numbers are allowed.
@ -232,12 +235,12 @@ If you use +:integer_only+ set to +true+, then it will use the +$$/\A[+\-]?\d+\Z
[source, ruby]
------------------------------------------------------------------
class Player < ActiveRecord::Base
validates_numericallity_of :points
validates_numericallity_of :games_played, :integer_only => true
validates_numericality_of :points
validates_numericality_of :games_played, :integer_only => true
end
------------------------------------------------------------------
The default error message for +validates_numericallity_of+ is "_is not a number_".
The default error message for +validates_numericality_of+ is "_is not a number_".
=== The +validates_presence_of+ helper
@ -282,7 +285,8 @@ There is a +:scope+ option that you can use to specify other attributes that mus
[source, ruby]
------------------------------------------------------------------
class Holiday < ActiveRecord::Base
validates_uniqueness_of :name, :scope => :year, :message => "Should happen once per year"
validates_uniqueness_of :name, :scope => :year,
:message => "Should happen once per year"
end
------------------------------------------------------------------
@ -324,9 +328,14 @@ As stated before, the +:on+ option lets you specify when the validation should h
[source, ruby]
------------------------------------------------------------------
class Person < ActiveRecord::Base
validates_uniqueness_of :email, :on => :create # => it will be possible to update email with a duplicated value
validates_numericallity_of :age, :on => :update # => it will be possible to create the record with a 'non-numerical age'
validates_presence_of :name, :on => :save # => that's the default
# => it will be possible to update email with a duplicated value
validates_uniqueness_of :email, :on => :create
# => it will be possible to create the record with a 'non-numerical age'
validates_numericality_of :age, :on => :update
# => the default
validates_presence_of :name, :on => :save
end
------------------------------------------------------------------
@ -367,7 +376,8 @@ Finally, it's possible to associate +:if+ and +:unless+ with a Ruby Proc object
[source, ruby]
------------------------------------------------------------------
class Account < ActiveRecord::Base
validates_confirmation_of :password, :unless => Proc.new { |a| a.password.blank? }
validates_confirmation_of :password,
:unless => Proc.new { |a| a.password.blank? }
end
------------------------------------------------------------------
@ -379,7 +389,8 @@ When the built-in validation helpers are not enough for your needs, you can writ
------------------------------------------------------------------
class Invoice < ActiveRecord::Base
def validate_on_create
errors.add(:expiration_date, "can't be in the past") if !expiration_date.blank? and expiration_date < Date.today
errors.add(:expiration_date, "can't be in the past") if
!expiration_date.blank? and expiration_date < Date.today
end
end
------------------------------------------------------------------
@ -389,14 +400,17 @@ If your validation rules are too complicated and you want to break them in small
[source, ruby]
------------------------------------------------------------------
class Invoice < ActiveRecord::Base
validate :expiration_date_cannot_be_in_the_past, :discount_cannot_be_more_than_total_value
validate :expiration_date_cannot_be_in_the_past,
:discount_cannot_be_more_than_total_value
def expiration_date_cannot_be_in_the_past
errors.add(:expiration_date, "can't be in the past") if !expiration_date.blank? and expiration_date < Date.today
errors.add(:expiration_date, "can't be in the past") if
!expiration_date.blank? and expiration_date < Date.today
end
def discount_cannot_be_greater_than_total_value
errors.add(:discount, "can't be greater than total value") unless discount <= total_value
errors.add(:discount, "can't be greater than total value") unless
discount <= total_value
end
end
------------------------------------------------------------------
@ -454,14 +468,16 @@ person.errors.on(:name) # => nil
person = Person.new(:name => "JD")
person.valid? # => false
person.errors.on(:name) # => "is too short (minimum is 3 characters)"
person.errors.on(:name)
# => "is too short (minimum is 3 characters)"
person = Person.new
person.valid? # => false
person.errors.on(:name) # => ["can't be blank", "is too short (minimum is 3 characters)"]
person.errors.on(:name)
# => ["can't be blank", "is too short (minimum is 3 characters)"]
------------------------------------------------------------------
* +clear+ is used when you intentionally wants to clear all the messages in the +errors+ collection.
* +clear+ is used when you intentionally want to clear all the messages in the +errors+ collection. However, calling +errors.clear+ upon an invalid object won't make it valid: the +errors+ collection will now be empty, but the next time you call +valid?+ or any method that tries to save this object to the database, the validations will run. If any of them fails, the +errors+ collection will get filled again.
[source, ruby]
------------------------------------------------------------------
@ -471,10 +487,15 @@ class Person < ActiveRecord::Base
end
person = Person.new
puts person.valid? # => false
person.errors.on(:name) # => ["can't be blank", "is too short (minimum is 3 characters)"]
person.valid? # => false
person.errors.on(:name)
# => ["can't be blank", "is too short (minimum is 3 characters)"]
person.errors.clear
person.errors # => nil
person.errors.empty? # => true
p.save # => false
p.errors.on(:name)
# => ["can't be blank", "is too short (minimum is 3 characters)"]
------------------------------------------------------------------
== Callbacks
@ -587,7 +608,7 @@ The +after_initialize+ and +after_find+ callbacks are a bit different from the o
== Halting Execution
As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks and the database operation to be executed. However, if at any moment one of the callback methods returns a boolean +false+ (not +nil+) value, this execution chain will be halted and the desired operation will not complete: your model will not get persisted in the database, or your records will not get deleted and so on.
As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks and the database operation to be executed. However, if at any moment one of the +before_create+, +before_save+, +before_update+ or +before_destroy+ callback methods returns a boolean +false+ (not +nil+) value, this execution chain will be halted and the desired operation will not complete: your model will not get persisted in the database, or your records will not get deleted and so on.
== Callback classes
@ -667,7 +688,7 @@ end
=== Registering observers
If you payed attention, you may be wondering where Active Record Observers are referenced in our applications, so they get instantiate and begin to interact with our models. For observers to work we need to register then in our application's *config/environment.rb* file. In this file there is a commented out line where we can define the observers that our application should load at start-up.
If you payed attention, you may be wondering where Active Record Observers are referenced in our applications, so they get instantiate and begin to interact with our models. For observers to work we need to register them somewhere. The usual place to do that is in our application's *config/environment.rb* file. In this file there is a commented out line where we can define the observers that our application should load at start-up.
[source, ruby]
------------------------------------------------------------------
@ -675,6 +696,10 @@ If you payed attention, you may be wondering where Active Record Observers are r
config.active_record.observers = :registration_observer, :auditor
------------------------------------------------------------------
You can uncomment the line with +config.active_record.observers+ and change the symbols for the name of the observers that should be registered.
It's also possible to register callbacks in any of the files living at *config/environments/*, if you want an observer to work only in a specific environment. There is not a +config.active_record.observers+ line at any of those files, but you can simply add it.
=== Where to put the observers' source files
By convention, you should always save your observers' source files inside *app/models*.

@ -185,7 +185,7 @@ SELECT * FROM users WHERE (created_at IN
'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:
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]
-------------------------------------------------------
@ -224,7 +224,7 @@ Client.all(:conditions =>
["created_at >= ? AND created_at <= ?", params[:start_date], params[:end_date]])
-------------------------------------------------------
Just like in Ruby.
Just like in Ruby. If you want a shorter syntax be sure to check out the <<_hash_conditions, Hash Conditions>> section later on in the guide.
=== Placeholder Conditions ===
@ -238,6 +238,40 @@ Client.all(:conditions =>
This makes for clearer readability if you have a large number of variable conditions.
=== Hash Conditions
Rails also allows you to pass in a hash conditions too 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:
[source, ruby]
-------------------------------------------------------
Client.all(:conditions => { :locked => true })
-------------------------------------------------------
The field name does not have to be a symbol it can also be a string:
[source, ruby]
-------------------------------------------------------
Client.all(:conditions => { 'locked' => true })
-------------------------------------------------------
The good thing about this is that we can pass in a range for our fields without it generating a large query as shown in the preamble of this section.
[source, ruby]
-------------------------------------------------------
Client.all(:conditions => { :created_at => ((Time.now.midnight - 1.day)..Time.now.midnight})
-------------------------------------------------------
This will find all clients created yesterday. This shows the shorter syntax for the examples in <<_array_conditions, Array Conditions>>
You can also join in tables and specify their columns in the hash:
[source, ruby]
-------------------------------------------------------
Client.all(:include => "orders", :conditions => { 'orders.created_at; => ((Time.now.midnight - 1.day)..Time.now.midnight})
-------------------------------------------------------
This will find all clients who have orders that were created yesterday.
== Ordering
If you're getting a set of records and want to force an order, you can use +Client.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.all(:order => "created_at desc")+
@ -619,7 +653,7 @@ This code specifies +clients.first_name+ just in case one of the join tables has
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.
For options, please see the parent section, <<_calculations, Calculations>>.
=== Average
@ -632,7 +666,7 @@ 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, Calculations>>
For options, please see the parent section, <<_calculations, Calculations>>.
=== Minimum
@ -677,6 +711,8 @@ Thanks to Mike Gunderloy for his tips on creating this guide.
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16[Lighthouse ticket]
* 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 http://rails.lighthouseapp.com/projects/16213/tickets/36-adding-an-example-for-using-distinct-to-ar-finders[this ticket]
* November 23 2008: Added documentation for +find_by_last+ and +find_by_bang!+
* November 21 2008: Fixed all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-13[this comment] and http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-14[this comment]

@ -984,7 +984,7 @@ end
This creates +comments+ as a _nested resource_ within +posts+. This is another part of capturing the hierarchical relationship that exists between posts and comments.
TIP: For more information on routing, see the link:../routing_outside_in[Rails Routing from the Outside In] guide.
TIP: For more information on routing, see the link:../routing_outside_in.html[Rails Routing from the Outside In] guide.
=== Generating a Controller

@ -12,7 +12,7 @@ Internationalization is a complex problem. Natural languages differ in so many w
=== The overall architecture of the library
To solve this the Ruby I18n gem is split into two parts:
Thus, the Ruby I18n gem is split into two parts:
* The public API which is just a Ruby module with a bunch of public methods and definitions how the library works.
* A shipped backend (which is intentionally named the Simple backend) that implements these methods.
@ -29,6 +29,14 @@ translate # lookup translations
localize # localize Date and Time objects to local formats
-------------------------------------------------------
These have the aliases #t and #l so you can use them like this:
[source, ruby]
-------------------------------------------------------
I18n.t 'store.title'
I18n.l Time.now
-------------------------------------------------------
There are also attribute readers and writers for the following attributes:
[source, ruby]
@ -46,9 +54,30 @@ There are just a few, simple steps to get up and running with a I18n support for
=== Configure the I18n module
First of all you want to tell the I18n library where it can find your custom translation files. You might also want to set your default locale to something else than English.
Rails will wire up all required settings for you with sane defaults. If you need different settings you can overwrite them easily.
You can pick whatever directory and translation file naming scheme makes sense for you. The simplest thing possible is probably to put the following into an initializer:
The I18n library will use English (:en) as a *default locale* by default. I.e if you don't set a different locale, :en will be used for looking up translations. Also, Rails adds all files from config/locales/*.rb,yml to your translations load path.
The *translations load path* (I18n.load_path) is just a Ruby Array of paths to your translation files that will be loaded automatically and available in your application. You can pick whatever directory and translation file naming scheme makes sense for you.
(Hint: The backend will lazy-load these translations when a translation is looked up for the first time. This makes it possible to just swap the backend with something else even after translations have already been announced.)
The default environment.rb says:
[source, ruby]
-------------------------------------------------------
# The internationalization framework can be changed
# to have another default locale (standard is :en) or more load paths.
# All files from config/locales/*.rb,yml are added automatically.
# config.i18n.load_path << Dir[File.join(RAILS_ROOT, 'my', 'locales', '*.{rb,yml}')]
# config.i18n.default_locale = :de
-------------------------------------------------------
=== Optional: custom I18n configuration setup
For the sake of completeness let's mention that if you do not want to use the environment for some reason you can always wire up things manually, too.
To tell the I18n library where it can find your custom translation files you can specify the load path anywhere in your application - just make sure it gets run before any translations are actually looked up. You might also want to change the default locale. The simplest thing possible is to put the following into an initializer:
[source, ruby]
-------------------------------------------------------
@ -58,14 +87,12 @@ You can pick whatever directory and translation file naming scheme makes sense f
I18n.load_path += Dir[ File.join(RAILS_ROOT, 'lib', 'locale', '*.{rb,yml}') ]
# you can omit this if you're happy with English as a default locale
I18n.default_locale = :"pt"
I18n.default_locale = :pt
-------------------------------------------------------
I18n.load_path is just a Ruby Array of paths to your translation files. The backend will lazy-load these translations when a translation is looked up for the first time. This makes it possible to just swap the backend with something else even after translations have already been announced.
=== Set the locale in each request
By default the I18n library will use the I18n.default_locale for looking up translations (if you do not specify a locale for a lookup) and this will, by default, en (English).
By default the I18n library will use :en (English) as a I18n.default_locale for looking up translations (if you do not specify a locale for a lookup).
If you want to translate your Rails application to a single language other than English you can set I18n.default_locale to your locale. If you want to change the locale on a per-request basis though you can set it in a before_filter on the ApplicationController like this:
@ -78,13 +105,15 @@ def set_locale
end
-------------------------------------------------------
This will already work for URLs where you pass the locale as a query parameter as in example.com?locale=pt-BR (which is what Google also does). (TODO hints about other approaches in the resources section).
This will already work for URLs where you pass the locale as a query parameter as in example.com?locale=pt (which is what Google also does).
TIP: For other URL designs, see http://rails-i18n.org/wiki/pages/how-to-encode-the-current-locale-in-the-url[How to encode the current locale in the URL].
Now you've initialized I18n support for your application and told it which locale should be used. With that in place you're now ready for the really interesting stuff.
=== Internationalize your application
== Internationalize your application
The process of "internationalization" usually means to abstract all strings and other locale specific bits out of your application (TODO reference to wikipedia). The process of "localization" means to then provide translations and localized formats for these bits.
The process of "internationalization" usually means to abstract all strings and other locale specific bits out of your application. The process of "localization" means to then provide translations and localized formats for these bits. <<1>>
So, let's internationalize something. You most probably have something like this in one of your applications:
@ -107,7 +136,9 @@ end
<p><%= flash[:notice] %></p>
-------------------------------------------------------
TODO screenshot
image:images/i18n/demo_untranslated.png[rails i18n demo untranslated]
=== Adding Translations
Obviously there are two strings that are localized to English. In order to internationalize this code replace these strings with calls to Rails' #t helper with a key that makes sense for the translation:
@ -125,39 +156,66 @@ end
<p><%= flash[:notice] %></p>
-------------------------------------------------------
TODO insert note about #t helper compared to I18n.t
TODO insert note/reference about structuring translation keys
When you now render this view it will show an error message that tells you that the translations for the keys :hello_world and :hello_flash are missing.
TODO screenshot
image:images/i18n/demo_translation_missing.png[rails i18n demo translation missing]
NOTE: Rails adds a +t+ (+translate+) helper method to your views so that you do not need to spell out +I18n.t+ all the time. Additionally this helper will catch missing translations and wrap the resulting error message into a &lt;span class="translation_missing"&gt;.
So let's add the missing translations (i.e. do the "localization" part):
[source, ruby]
-------------------------------------------------------
# lib/locale/en.yml
en-US:
# config/locale/en.yml
en:
hello_world: Hello World
hello_flash: Hello Flash
# lib/locale/pirate.yml
# config/locale/pirate.yml
pirate:
hello_world: Ahoy World
hello_flash: Ahoy Flash
-------------------------------------------------------
There you go. Your application now shows:
There you go. Because you haven't changed the default_locale I18n will use English. Your application now shows:
TODO screenshot
image:images/i18n/demo_translated_english.png[rails i18n demo translated to english]
And when you change the URL to pass the pirate locale you get:
image:images/i18n/demo_translated_pirate.png[rails i18n demo translated to pirate]
NOTE You need to restart the server when you add new locale files.
=== Adding Date/Time formats
Ok, let's add a timestamp to the view so we can demo the date/time localization feature as well. To localize the time format you pass the Time object to I18n.l or (preferably) use Rails' #l helper. You can pick a format by passing the :format option, by default the :default format is used.
[source, ruby]
-------------------------------------------------------
I18n.t 'store.title'
I18n.l Time.now
# app/views/home/index.html.erb
<h1><%=t :hello_world %></h1>
<p><%= flash[:notice] %></p
<p><%= l Time.now, :format => :short %></p>
-------------------------------------------------------
And in our pirate translations file let's add a time format (it's already there in Rails' defaults for English):
[source, ruby]
-------------------------------------------------------
# config/locale/pirate.yml
pirate:
time:
formats:
short: "arrrround %H'ish"
-------------------------------------------------------
So that would give you:
image:images/i18n/demo_localized_pirate.png[rails i18n demo localized time to pirate]
NOTE Right now you might need to add some more date/time formats in order to make the I18n backend work as expected. See the http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale[rails-i18n repository] for starting points.
== Overview of the I18n API features
@ -218,7 +276,7 @@ I18n.t :missing, :default => 'Not here'
If the default value is a Symbol it will be used as a key and translated. One can provide multiple values as default. The first one that results in a value will be returned.
E.g. the following first tries to translate the key :missing and then the key :also_missing. As both do not yield a result the string Not here will be returned:
E.g. the following first tries to translate the key :missing and then the key :also_missing. As both do not yield a result the string "Not here" will be returned:
[source, ruby]
-------------------------------------------------------
@ -246,28 +304,29 @@ I18n.t 'active_record.error_messages'
=== Interpolation
TODO explain what this is good for
In many cases you want to abstract your translations so that variables can be interpolated into the translation. For this reason the I18n API provides an interpolation feature.
All options besides :default and :scope that are passed to #translate will be interpolated to the translation:
[source, ruby]
-------------------------------------------------------
I18n.backend.store_translations 'en', :thanks => 'Thanks {{name}}!'
I18n.backend.store_translations :en, :thanks => 'Thanks {{name}}!'
I18n.translate :thanks, :name => 'Jeremy'
# => 'Thanks Jeremy!'
-------------------------------------------------------
If a translation uses :default or :scope as a interpolation variable an I18n::ReservedInterpolationKey exception is raised. If a translation expects an interpolation variable but it has not been passed to #translate an I18n::MissingInterpolationArgument exception is raised.
=== Pluralization
TODO explain what this is good for
In English there's only a singular and a plural form for a given string, e.g. "1 message" and "2 messages". Other languages (http://www.unicode.org/cldr/data/charts/supplemental/language_plural_rules.html#ar[Arabic], http://www.unicode.org/cldr/data/charts/supplemental/language_plural_rules.html#ja[Japanese], http://www.unicode.org/cldr/data/charts/supplemental/language_plural_rules.html#ru[Russian] and many more) have different grammars that have additional or less http://www.unicode.org/cldr/data/charts/supplemental/language_plural_rules.html[plural forms]. Thus, the I18n API provides a flexible pluralization feature.
The :count interpolation variable has a special role in that it both is interpolated to the translation and used to pick a pluralization from the translations according to the pluralization rules defined by CLDR:
[source, ruby]
-------------------------------------------------------
I18n.backend.store_translations 'en-US', :inbox => { # TODO change this
I18n.backend.store_translations :en, :inbox => {
:one => '1 message',
:other => '{{count}} messages'
}
@ -275,7 +334,7 @@ I18n.translate :inbox, :count => 2
# => '2 messages'
-------------------------------------------------------
The algorithm for pluralizations in en-US is as simple as:
The algorithm for pluralizations in :en is as simple as:
[source, ruby]
-------------------------------------------------------
@ -294,7 +353,7 @@ If no locale is passed I18n.locale is used:
[source, ruby]
-------------------------------------------------------
I18n.locale = :'de'
I18n.locale = :de
I18n.t :foo
I18n.l Time.now
-------------------------------------------------------
@ -303,27 +362,27 @@ Explicitely passing a locale:
[source, ruby]
-------------------------------------------------------
I18n.t :foo, :locale => :'de'
I18n.l Time.now, :locale => :'de'
I18n.t :foo, :locale => :de
I18n.l Time.now, :locale => :de
-------------------------------------------------------
I18n.locale defaults to I18n.default_locale which defaults to :'en'. The default locale can be set like this:
I18n.locale defaults to I18n.default_locale which defaults to :en. The default locale can be set like this:
[source, ruby]
-------------------------------------------------------
I18n.default_locale = :'de'
I18n.default_locale = :de
-------------------------------------------------------
== How to store your custom translations
The shipped Simple backend allows you to store translations in both plain Ruby and YAML format. (2)
The shipped Simple backend allows you to store translations in both plain Ruby and YAML format. <<2>>
For example a Ruby Hash providing translations can look like this:
[source, ruby]
-------------------------------------------------------
{
:'pt-BR' => {
:pt => {
:foo => {
:bar => "baz"
}
@ -335,18 +394,18 @@ The equivalent YAML file would look like this:
[source, ruby]
-------------------------------------------------------
"pt-BR":
pt:
foo:
bar: baz
-------------------------------------------------------
As you see in both cases the toplevel key is the locale. :foo is a namespace key and :bar is the key for the translation "baz".
Here is a "real" example from the ActiveSupport en-US translations YAML file:
Here is a "real" example from the ActiveSupport en.yml translations YAML file:
[source, ruby]
-------------------------------------------------------
"en":
en:
date:
formats:
default: "%Y-%m-%d"
@ -364,12 +423,16 @@ I18n.t :short, :scope => 'date.formats'
I18n.t :short, :scope => [:date, :formats]
-------------------------------------------------------
Generally we recommend using YAML as a format for storing translations. There are cases though where you want to store Ruby lambdas as part of your locale data, e.g. for special date
=== Translations for ActiveRecord models
You can use the methods Model.human_name and Model.human_attribute_name(attribute) to transparently lookup translations for your model and attribute names.
For example when you add the following translations:
[source, ruby]
-------------------------------------------------------
en:
activerecord:
models:
@ -378,6 +441,7 @@ en:
user:
login: "Handle"
# will translate User attribute "login" as "Handle"
-------------------------------------------------------
Then User.human_name will return "Dude" and User.human_attribute_name(:login) will return "Handle".
@ -396,24 +460,21 @@ class User < ActiveRecord::Base
end
-------------------------------------------------------
The key for the error message in this case is :blank. So ActiveRecord will first try to look up an error message with:
The key for the error message in this case is :blank. ActiveRecord will lookup this key in the namespaces:
[source, ruby]
-------------------------------------------------------
activerecord.errors.messages.models.[model_name].attributes.[attribute_name]
activerecord.errors.messages.models.[model_name]
activerecord.errors.messages
-------------------------------------------------------
Thus, in our example it will try the following keys in this order and return the first result:
[source, ruby]
-------------------------------------------------------
activerecord.errors.messages.models.user.attributes.name.blank
-------------------------------------------------------
If it's not there it will try:
[source, ruby]
-------------------------------------------------------
activerecord.errors.messages.models.user.blank
-------------------------------------------------------
If this is also not there it will use the default message from:
[source, ruby]
-------------------------------------------------------
activerecord.errors.messages.blank
-------------------------------------------------------
@ -447,28 +508,27 @@ The translated model name and translated attribute name are always available for
So, for example, instead of the default error message "can not be blank" you could use the attribute name like this: "Please fill in your {{attribute}}".
Count and/or value are available where applicable. Count can be used for pluralization if present:
count and/or value are available where applicable. Count can be used for pluralization if present:
[grid="all"]
`---------------------------`----------------`---------------`----------------
validation with option message interpolation
validates_confirmation_of - :confirmation -
validates_acceptance_of - :accepted -
validates_presence_of - :blank -
validates_length_of :within, :in :too_short count
validates_length_of :within, :in :too_long count
validates_length_of :is :wrong_length count
validates_length_of :minimum :too_short count
validates_length_of :maximum :too_long count
validates_uniqueness_of - :taken value
validates_format_of - :invalid value
validates_inclusion_of - :inclusion value
validates_exclusion_of - :exclusion value
validates_associated - :invalid value
validates_numericality_of - :not_a_number value
validates_numericality_of :odd :odd value
validates_numericality_of :even :even value
------------------------------------------------------------------------------
|==================================================================================
| validation | with option | message | interpolation
| validates_confirmation_of | - | :confirmation | -
| validates_acceptance_of | - | :accepted | -
| validates_presence_of | - | :blank | -
| validates_length_of | :within, :in | :too_short | count
| validates_length_of | :within, :in | :too_long | count
| validates_length_of | :is | :wrong_length | count
| validates_length_of | :minimum | :too_short | count
| validates_length_of | :maximum | :too_long | count
| validates_uniqueness_of | - | :taken | value
| validates_format_of | - | :invalid | value
| validates_inclusion_of | - | :inclusion | value
| validates_exclusion_of | - | :exclusion | value
| validates_associated | - | :invalid | value
| validates_numericality_of | - | :not_a_number | value
| validates_numericality_of | :odd | :odd | value
| validates_numericality_of | :even | :even | value
|==================================================================================
==== Translations for the ActiveRecord error_messages_for helper
@ -479,14 +539,14 @@ Rails ships with the following translations:
[source, ruby]
-------------------------------------------------------
"en":
en:
activerecord:
errors:
template:
header:
one: "1 error prohibited this {{model}} from being saved"
other: "{{count}} errors prohibited this {{model}} from being saved"
body: "There were problems with the following fields:"
body: "There were problems with the following fields:"
-------------------------------------------------------
@ -496,11 +556,12 @@ Rails uses fixed strings and other localizations, such as format strings and oth
TODO list helpers and available keys
== Customize your I18n setup
=== Using different backends
For several reasons the shipped Simple backend only does the "simplest thing that ever could work" _for Ruby on Rails_ (1) ... which means that it is only guaranteed to work for English and, as a side effect, languages that are very similar to English. Also, the simple backend is only capable of reading translations but can not dynamically store them to any format.
For several reasons the shipped Simple backend only does the "simplest thing that ever could work" _for Ruby on Rails_ <<3>> ... which means that it is only guaranteed to work for English and, as a side effect, languages that are very similar to English. Also, the simple backend is only capable of reading translations but can not dynamically store them to any format.
That does not mean you're stuck with these limitations though. The Ruby I18n gem makes it very easy to exchange the Simple backend implementation with something else that fits better for your needs. E.g. you could exchange it with Globalize's Static backend:
@ -509,30 +570,59 @@ That does not mean you're stuck with these limitations though. The Ruby I18n gem
I18n.backend = Globalize::Backend::Static.new
-------------------------------------------------------
TODO expand this ...? list some backends and their features?
=== Using different exception handlers
TODO
The I18n API defines the following exceptions that will be raised by backends when the corresponding unexpected conditions occur:
* Explain what exceptions are raised and why we are using exceptions for communication from backend to frontend.
* Explain the default behaviour.
* Explain the :raise option
[source, ruby]
-------------------------------------------------------
MissingTranslationData # no translation was found for the requested key
InvalidLocale # the locale set to I18n.locale is invalid (e.g. nil)
InvalidPluralizationData # a count option was passed but the translation data is not suitable for pluralization
MissingInterpolationArgument # the translation expects an interpolation argument that has not been passed
ReservedInterpolationKey # the translation contains a reserved interpolation variable name (i.e. one of: scope, default)
UnknownFileType # the backend does not know how to handle a file type that was added to I18n.load_path
-------------------------------------------------------
* Example 1: the Rails #t helper uses a custom exception handler that catches I18n::MissingTranslationData and wraps the message into a span with the CSS class "translation_missing"
* Example 2: for tests you might want a handler that just raises all exceptions all the time
* Example 3: a handler
The I18n API will catch all of these exceptions when they were thrown in the backend and pass them to the default_exception_handler method. This method will re-raise all exceptions except for MissingTranslationData exceptions. When a MissingTranslationData exception has been caught it will return the exceptions error message string containing the missing key/scope.
The reason for this is that during development you'd usually want your views to still render even though a translation is missing.
In other contexts you might want to change this behaviour though. E.g. the default exception handling does not allow to catch missing translations during automated tests easily. For this purpose a different exception handler can be specified. The specified exception handler must be a method on the I18n module:
[source, ruby]
-------------------------------------------------------
module I18n
def just_raise_that_exception(*args)
raise args.first
end
end
I18n.exception_handler = :just_raise_that_exception
-------------------------------------------------------
This would re-raise all caught exceptions including MissingTranslationData.
Another example where the default behaviour is less desirable is the Rails TranslationHelper which provides the method #t (as well as #translate). When a MissingTranslationData exception occurs in this context the helper wraps the message into a span with the css class translation_missing.
To do so the helper forces I18n#translate to raise exceptions no matter what exception handler is defined by setting the :raise option:
[source, ruby]
-------------------------------------------------------
I18n.t :foo, :raise => true # always re-raises exceptions from the backend
-------------------------------------------------------
== Resources
* http://rails-i18n.org
== Footnotes
(1) One of these reasons is that we don't want to any unnecessary load for applications that do not need any I18n capabilities, so we need to keep the I18n library as simple as possible for English. Another reason is that it is virtually impossible to implement a one-fits-all solution for all problems related to I18n for all existing languages. So a solution that allows us to exchange the entire implementation easily is appropriate anyway. This also makes it much easier to experiment with custom features and extensions.
[[[1]]] Or, to quote http://en.wikipedia.org/wiki/Internationalization_and_localization[Wikipedia]: _"Internationalization is the process of designing a software application so that it can be adapted to various languages and regions without engineering changes. Localization is the process of adapting software for a specific region or language by adding locale-specific components and translating text."_
(2) Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files.
[[[2]]] Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files.
[[[3]]] One of these reasons is that we don't want to any unnecessary load for applications that do not need any I18n capabilities, so we need to keep the I18n library as simple as possible for English. Another reason is that it is virtually impossible to implement a one-fits-all solution for all problems related to I18n for all existing languages. So a solution that allows us to exchange the entire implementation easily is appropriate anyway. This also makes it much easier to experiment with custom features and extensions.
== Credits

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

@ -226,18 +226,18 @@ Above +rake db:migrate+ runs any pending migrations on the _developemnt_ environ
NOTE: +db:test:prepare+ will fail with an error if db/schema.rb doesn't exists.
==== Rake Tasks for Preparing you Application for Testing ==
==== Rake Tasks for Preparing your Application for Testing ====
[grid="all"]
------------------------------------------------------------------------------------
Tasks Description
------------------------------------------------------------------------------------
+rake db:test:clone+ Recreate the test database from the current environment's database schema
+rake db:test:clone_structure+ Recreate the test databases from the development structure
+rake db:test:load+ Recreate the test database from the current +schema.rb+
+rake db:test:prepare+ Check for pending migrations and load the test schema
+rake db:test:purge+ Empty the test database.
------------------------------------------------------------------------------------
|------------------------------------------------------------------------------------
|Tasks Description
|------------------------------------------------------------------------------------
|+rake db:test:clone+ Recreate the test database from the current environment's database schema
|+rake db:test:clone_structure+ Recreate the test databases from the development structure
|+rake db:test:load+ Recreate the test database from the current +schema.rb+
|+rake db:test:prepare+ Check for pending migrations and load the test schema
|+rake db:test:purge+ Empty the test database.
|------------------------------------------------------------------------------------
TIP: You can see all these rake tasks and their descriptions by running +rake \-\-tasks \-\-describe+

@ -30,7 +30,7 @@ def plugin_names
end
# The Rails::Plugin::FileSystemLocator will try to locate plugins by examining the directories
# the the paths given in configuration.plugin_paths. Any plugins that can be found are returned
# in the paths given in configuration.plugin_paths. Any plugins that can be found are returned
# in a list.
#
# The criteria for a valid plugin in this case is found in Rails::Plugin#valid?, although