提交 1ce40ca5 编写于 作者: N Neeraj Singh

ensuring that description does not exceed 100 columns

上级 b8d9d9ce
...@@ -106,9 +106,10 @@ def construct_scope ...@@ -106,9 +106,10 @@ def construct_scope
:limit => @reflection.options[:limit] } } :limit => @reflection.options[:limit] } }
end end
# Join tables with additional columns on top of the two foreign keys must be considered ambiguous unless a select # Join tables with additional columns on top of the two foreign keys must be considered
# clause has been explicitly defined. Otherwise you can get broken records back, if, for example, the join column also has # ambiguous unless a select clause has been explicitly defined. Otherwise you can get
# an id column. This will then overwrite the id column of the records coming back. # broken records back, if, for example, the join column also has an id column. This will
# then overwrite the id column of the records coming back.
def finding_with_ambiguous_select?(select_clause) def finding_with_ambiguous_select?(select_clause)
!select_clause && columns.size != 2 !select_clause && columns.size != 2
end end
......
...@@ -24,9 +24,10 @@ def destroy(*records) ...@@ -24,9 +24,10 @@ def destroy(*records)
end end
end end
# Returns the size of the collection by executing a SELECT COUNT(*) query if the collection hasn't been loaded and # Returns the size of the collection by executing a SELECT COUNT(*) query if the collection hasn't been
# calling collection.size if it has. If it's more likely than not that the collection does have a size larger than zero, # loaded and calling collection.size if it has. If it's more likely than not that the collection does
# and you need to fetch that collection afterwards, it'll take one fewer SELECT query if you use #length. # have a size larger than zero, and you need to fetch that collection afterwards, it'll take one fewer
# SELECT query if you use #length.
def size def size
return @owner.send(:read_attribute, cached_counter_attribute_name) if has_cached_counter? return @owner.send(:read_attribute, cached_counter_attribute_name) if has_cached_counter?
return @target.size if loaded? return @target.size if loaded?
......
...@@ -14,7 +14,8 @@ module TimeZoneConversion ...@@ -14,7 +14,8 @@ module TimeZoneConversion
module ClassMethods module ClassMethods
protected protected
# Defined for all +datetime+ and +timestamp+ attributes when +time_zone_aware_attributes+ are enabled. # Defined for all +datetime+ and +timestamp+ attributes when +time_zone_aware_attributes+ are enabled.
# This enhanced read method automatically converts the UTC time stored in the database to the time zone stored in Time.zone. # This enhanced read method automatically converts the UTC time stored in the database to the time
# zone stored in Time.zone.
def define_method_attribute(attr_name) def define_method_attribute(attr_name)
if create_time_zone_conversion_attribute?(attr_name, columns_hash[attr_name]) if create_time_zone_conversion_attribute?(attr_name, columns_hash[attr_name])
method_body, line = <<-EOV, __LINE__ + 1 method_body, line = <<-EOV, __LINE__ + 1
......
...@@ -14,8 +14,8 @@ def define_method_attribute=(attr_name) ...@@ -14,8 +14,8 @@ def define_method_attribute=(attr_name)
end end
end end
# Updates the attribute identified by <tt>attr_name</tt> with the specified +value+. Empty strings for fixnum and float # Updates the attribute identified by <tt>attr_name</tt> with the specified +value+. Empty strings
# columns are turned into +nil+. # for fixnum and float columns are turned into +nil+.
def write_attribute(attr_name, value) def write_attribute(attr_name, value)
attr_name = attr_name.to_s attr_name = attr_name.to_s
attr_name = self.class.primary_key if attr_name == 'id' attr_name = self.class.primary_key if attr_name == 'id'
......
...@@ -26,8 +26,8 @@ module ActiveRecord ...@@ -26,8 +26,8 @@ module ActiveRecord
# <tt>after_rollback</tt>. # <tt>after_rollback</tt>.
# #
# That's a total of ten callbacks, which gives you immense power to react and prepare for each state in the # That's a total of ten callbacks, which gives you immense power to react and prepare for each state in the
# Active Record lifecycle. The sequence for calling <tt>Base#save</tt> for an existing record is similar, except that each # Active Record lifecycle. The sequence for calling <tt>Base#save</tt> for an existing record is similar,
# <tt>_on_create</tt> callback is replaced by the corresponding <tt>_on_update</tt> callback. # except that each <tt>_on_create</tt> callback is replaced by the corresponding <tt>_on_update</tt> callback.
# #
# Examples: # Examples:
# class CreditCard < ActiveRecord::Base # class CreditCard < ActiveRecord::Base
...@@ -55,9 +55,9 @@ module ActiveRecord ...@@ -55,9 +55,9 @@ module ActiveRecord
# #
# == Inheritable callback queues # == Inheritable callback queues
# #
# Besides the overwritable callback methods, it's also possible to register callbacks through the use of the callback macros. # Besides the overwritable callback methods, it's also possible to register callbacks through the
# Their main advantage is that the macros add behavior into a callback queue that is kept intact down through an inheritance # use of the callback macros. Their main advantage is that the macros add behavior into a callback
# hierarchy. Example: # queue that is kept intact down through an inheritance hierarchy.
# #
# class Topic < ActiveRecord::Base # class Topic < ActiveRecord::Base
# before_destroy :destroy_author # before_destroy :destroy_author
...@@ -67,9 +67,9 @@ module ActiveRecord ...@@ -67,9 +67,9 @@ module ActiveRecord
# before_destroy :destroy_readers # before_destroy :destroy_readers
# end # end
# #
# Now, when <tt>Topic#destroy</tt> is run only +destroy_author+ is called. When <tt>Reply#destroy</tt> is run, both +destroy_author+ and # Now, when <tt>Topic#destroy</tt> is run only +destroy_author+ is called. When <tt>Reply#destroy</tt> is
# +destroy_readers+ are called. Contrast this to the situation where we've implemented the save behavior through overwriteable # run, both +destroy_author+ and +destroy_readers+ are called. Contrast this to the situation where
# methods: # we've implemented the save behavior through overwriteable methods:
# #
# class Topic < ActiveRecord::Base # class Topic < ActiveRecord::Base
# def before_destroy() destroy_author end # def before_destroy() destroy_author end
...@@ -79,20 +79,21 @@ module ActiveRecord ...@@ -79,20 +79,21 @@ module ActiveRecord
# def before_destroy() destroy_readers end # def before_destroy() destroy_readers end
# end # end
# #
# In that case, <tt>Reply#destroy</tt> would only run +destroy_readers+ and _not_ +destroy_author+. So, use the callback macros when # In that case, <tt>Reply#destroy</tt> would only run +destroy_readers+ and _not_ +destroy_author+.
# you want to ensure that a certain callback is called for the entire hierarchy, and use the regular overwriteable methods # So, use the callback macros when you want to ensure that a certain callback is called for the entire
# when you want to leave it up to each descendant to decide whether they want to call +super+ and trigger the inherited callbacks. # hierarchy, and use the regular overwriteable methods when you want to leave it up to each descendant
# to decide whether they want to call +super+ and trigger the inherited callbacks.
# #
# *IMPORTANT:* In order for inheritance to work for the callback queues, you must specify the callbacks before specifying the # *IMPORTANT:* In order for inheritance to work for the callback queues, you must specify the
# associations. Otherwise, you might trigger the loading of a child before the parent has registered the callbacks and they won't # callbacks before specifying the associations. Otherwise, you might trigger the loading of a
# be inherited. # child before the parent has registered the callbacks and they won't be inherited.
# #
# == Types of callbacks # == Types of callbacks
# #
# There are four types of callbacks accepted by the callback macros: Method references (symbol), callback objects, # There are four types of callbacks accepted by the callback macros: Method references (symbol), callback objects,
# inline methods (using a proc), and inline eval methods (using a string). Method references and callback objects are the # inline methods (using a proc), and inline eval methods (using a string). Method references and callback objects
# recommended approaches, inline methods using a proc are sometimes appropriate (such as for creating mix-ins), and inline # are the recommended approaches, inline methods using a proc are sometimes appropriate (such as for
# eval methods are deprecated. # creating mix-ins), and inline eval methods are deprecated.
# #
# The method reference callbacks work by specifying a protected or private method available in the object, like this: # The method reference callbacks work by specifying a protected or private method available in the object, like this:
# #
...@@ -169,15 +170,15 @@ module ActiveRecord ...@@ -169,15 +170,15 @@ module ActiveRecord
# end # end
# end # end
# #
# The callback macros usually accept a symbol for the method they're supposed to run, but you can also pass a "method string", # The callback macros usually accept a symbol for the method they're supposed to run, but you can also
# which will then be evaluated within the binding of the callback. Example: # pass a "method string", which will then be evaluated within the binding of the callback. Example:
# #
# class Topic < ActiveRecord::Base # class Topic < ActiveRecord::Base
# before_destroy 'self.class.delete_all "parent_id = #{id}"' # before_destroy 'self.class.delete_all "parent_id = #{id}"'
# end # end
# #
# Notice that single quotes (') are used so the <tt>#{id}</tt> part isn't evaluated until the callback is triggered. Also note that these # Notice that single quotes (') are used so the <tt>#{id}</tt> part isn't evaluated until the callback
# inline callbacks can be stacked just like the regular ones: # is triggered. Also note that these inline callbacks can be stacked just like the regular ones:
# #
# class Topic < ActiveRecord::Base # class Topic < ActiveRecord::Base
# before_destroy 'self.class.delete_all "parent_id = #{id}"', # before_destroy 'self.class.delete_all "parent_id = #{id}"',
...@@ -186,22 +187,24 @@ module ActiveRecord ...@@ -186,22 +187,24 @@ module ActiveRecord
# #
# == The +after_find+ and +after_initialize+ exceptions # == The +after_find+ and +after_initialize+ exceptions
# #
# Because +after_find+ and +after_initialize+ are called for each object found and instantiated by a finder, such as <tt>Base.find(:all)</tt>, we've had # Because +after_find+ and +after_initialize+ are called for each object found and instantiated by a finder,
# to implement a simple performance constraint (50% more speed on a simple test case). Unlike all the other callbacks, +after_find+ and # such as <tt>Base.find(:all)</tt>, we've had to implement a simple performance constraint (50% more speed
# +after_initialize+ will only be run if an explicit implementation is defined (<tt>def after_find</tt>). In that case, all of the # on a simple test case). Unlike all the other callbacks, +after_find+ and +after_initialize+ will only be
# run if an explicit implementation is defined (<tt>def after_find</tt>). In that case, all of the
# callback types will be called. # callback types will be called.
# #
# == <tt>before_validation*</tt> returning statements # == <tt>before_validation*</tt> returning statements
# #
# If the returning value of a +before_validation+ callback can be evaluated to +false+, the process will be aborted and <tt>Base#save</tt> will return +false+. # If the returning value of a +before_validation+ callback can be evaluated to +false+, the process will be
# If Base#save! is called it will raise a ActiveRecord::RecordInvalid exception. # aborted and <tt>Base#save</tt> will return +false+. If Base#save! is called it will raise a
# Nothing will be appended to the errors object. # ActiveRecord::RecordInvalid exception. Nothing will be appended to the errors object.
# #
# == Canceling callbacks # == Canceling callbacks
# #
# If a <tt>before_*</tt> callback returns +false+, all the later callbacks and the associated action are cancelled. If an <tt>after_*</tt> callback returns # If a <tt>before_*</tt> callback returns +false+, all the later callbacks and the associated action are
# +false+, all the later callbacks are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks # cancelled. If an <tt>after_*</tt> callback returns +false+, all the later callbacks are cancelled.
# defined as methods on the model, which are called last. # Callbacks are generally run in the order they are defined, with the exception of callbacks defined as
# methods on the model, which are called last.
# #
# == Transactions # == Transactions
# #
...@@ -217,7 +220,8 @@ module ActiveRecord ...@@ -217,7 +220,8 @@ module ActiveRecord
# #
# == Debugging callbacks # == Debugging callbacks
# #
# To list the methods and procs registered with a particular callback, append <tt>_callback_chain</tt> to the callback name that you wish to list and send that to your class from the Rails console: # To list the methods and procs registered with a particular callback, append <tt>_callback_chain</tt> to
# the callback name that you wish to list and send that to your class from the Rails console:
# #
# >> Topic.after_save_callback_chain # >> Topic.after_save_callback_chain
# => [#<ActiveSupport::Callbacks::Callback:0x3f6a448 # => [#<ActiveSupport::Callbacks::Callback:0x3f6a448
......
...@@ -23,7 +23,8 @@ module Format ...@@ -23,7 +23,8 @@ module Format
# #
# +name+ is the column's name, such as <tt>supplier_id</tt> in <tt>supplier_id int(11)</tt>. # +name+ is the column's name, such as <tt>supplier_id</tt> in <tt>supplier_id int(11)</tt>.
# +default+ is the type-casted default value, such as +new+ in <tt>sales_stage varchar(20) default 'new'</tt>. # +default+ is the type-casted default value, such as +new+ in <tt>sales_stage varchar(20) default 'new'</tt>.
# +sql_type+ is used to extract the column's length, if necessary. For example +60+ in <tt>company_name varchar(60)</tt>. # +sql_type+ is used to extract the column's length, if necessary. For example +60+ in
# <tt>company_name varchar(60)</tt>.
# It will be mapped to one of the standard Rails SQL types in the <tt>type</tt> attribute. # It will be mapped to one of the standard Rails SQL types in the <tt>type</tt> attribute.
# +null+ determines if this column allows +NULL+ values. # +null+ determines if this column allows +NULL+ values.
def initialize(name, default, sql_type = nil, null = true) def initialize(name, default, sql_type = nil, null = true)
...@@ -359,7 +360,8 @@ def [](name) ...@@ -359,7 +360,8 @@ def [](name)
# #
# Available options are (none of these exists by default): # Available options are (none of these exists by default):
# * <tt>:limit</tt> - # * <tt>:limit</tt> -
# Requests a maximum column length. This is number of characters for <tt>:string</tt> and <tt>:text</tt> columns and number of bytes for :binary and :integer columns. # Requests a maximum column length. This is number of characters for <tt>:string</tt> and
# <tt>:text</tt> columns and number of bytes for :binary and :integer columns.
# * <tt>:default</tt> - # * <tt>:default</tt> -
# The column's default value. Use nil for NULL. # The column's default value. Use nil for NULL.
# * <tt>:null</tt> - # * <tt>:null</tt> -
...@@ -462,8 +464,8 @@ def [](name) ...@@ -462,8 +464,8 @@ def [](name)
# TableDefinition#timestamps that'll add created_at and +updated_at+ as datetimes. # TableDefinition#timestamps that'll add created_at and +updated_at+ as datetimes.
# #
# TableDefinition#references will add an appropriately-named _id column, plus a corresponding _type # TableDefinition#references will add an appropriately-named _id column, plus a corresponding _type
# column if the <tt>:polymorphic</tt> option is supplied. If <tt>:polymorphic</tt> is a hash of options, these will be # column if the <tt>:polymorphic</tt> option is supplied. If <tt>:polymorphic</tt> is a hash of
# used when creating the <tt>_type</tt> column. So what can be written like this: # options, these will be used when creating the <tt>_type</tt> column. So what can be written like this:
# #
# create_table :taggings do |t| # create_table :taggings do |t|
# t.integer :tag_id, :tagger_id, :taggable_id # t.integer :tag_id, :tagger_id, :taggable_id
......
...@@ -278,7 +278,8 @@ def select_rows(sql, name = nil) ...@@ -278,7 +278,8 @@ def select_rows(sql, name = nil)
rows rows
end end
# Executes a SQL query and returns a MySQL::Result object. Note that you have to free the Result object after you're done using it. # Executes a SQL query and returns a MySQL::Result object. Note that you have to free
# the Result object after you're done using it.
def execute(sql, name = nil) #:nodoc: def execute(sql, name = nil) #:nodoc:
if name == :skip_logging if name == :skip_logging
@connection.query(sql) @connection.query(sql)
......
...@@ -183,10 +183,14 @@ module ConnectionAdapters ...@@ -183,10 +183,14 @@ module ConnectionAdapters
# * <tt>:username</tt> - Defaults to nothing. # * <tt>:username</tt> - Defaults to nothing.
# * <tt>:password</tt> - Defaults to nothing. # * <tt>:password</tt> - Defaults to nothing.
# * <tt>:database</tt> - The name of the database. No default, must be provided. # * <tt>:database</tt> - The name of the database. No default, must be provided.
# * <tt>:schema_search_path</tt> - An optional schema search path for the connection given as a string of comma-separated schema names. This is backward-compatible with the <tt>:schema_order</tt> option. # * <tt>:schema_search_path</tt> - An optional schema search path for the connection given
# * <tt>:encoding</tt> - An optional client encoding that is used in a <tt>SET client_encoding TO <encoding></tt> call on the connection. # as a string of comma-separated schema names. This is backward-compatible with the <tt>:schema_order</tt> option.
# * <tt>:min_messages</tt> - An optional client min messages that is used in a <tt>SET client_min_messages TO <min_messages></tt> call on the connection. # * <tt>:encoding</tt> - An optional client encoding that is used in a <tt>SET client_encoding TO
# * <tt>:allow_concurrency</tt> - If true, use async query methods so Ruby threads don't deadlock; otherwise, use blocking query methods. # <encoding></tt> call on the connection.
# * <tt>:min_messages</tt> - An optional client min messages that is used in a
# <tt>SET client_min_messages TO <min_messages></tt> call on the connection.
# * <tt>:allow_concurrency</tt> - If true, use async query methods so Ruby threads don't deadlock;
# otherwise, use blocking query methods.
class PostgreSQLAdapter < AbstractAdapter class PostgreSQLAdapter < AbstractAdapter
ADAPTER_NAME = 'PostgreSQL'.freeze ADAPTER_NAME = 'PostgreSQL'.freeze
......
...@@ -29,8 +29,8 @@ def binary_to_string(value) ...@@ -29,8 +29,8 @@ def binary_to_string(value)
end end
end end
# The SQLite adapter works with both the 2.x and 3.x series of SQLite with the sqlite-ruby drivers (available both as gems and # The SQLite adapter works with both the 2.x and 3.x series of SQLite with the sqlite-ruby
# from http://rubyforge.org/projects/sqlite-ruby/). # drivers (available both as gems and from http://rubyforge.org/projects/sqlite-ruby/).
# #
# Options: # Options:
# #
......
...@@ -30,7 +30,8 @@ class AssociationTypeMismatch < ActiveRecordError ...@@ -30,7 +30,8 @@ class AssociationTypeMismatch < ActiveRecordError
class SerializationTypeMismatch < ActiveRecordError class SerializationTypeMismatch < ActiveRecordError
end end
# Raised when adapter not specified on connection (or configuration file <tt>config/database.yml</tt> misses adapter field). # Raised when adapter not specified on connection (or configuration file <tt>config/database.yml</tt>
# misses adapter field).
class AdapterNotSpecified < ActiveRecordError class AdapterNotSpecified < ActiveRecordError
end end
...@@ -38,7 +39,8 @@ class AdapterNotSpecified < ActiveRecordError ...@@ -38,7 +39,8 @@ class AdapterNotSpecified < ActiveRecordError
class AdapterNotFound < ActiveRecordError class AdapterNotFound < ActiveRecordError
end end
# Raised when connection to the database could not been established (for example when <tt>connection=</tt> is given a nil object). # Raised when connection to the database could not been established (for example when <tt>connection=</tt>
# is given a nil object).
class ConnectionNotEstablished < ActiveRecordError class ConnectionNotEstablished < ActiveRecordError
end end
...@@ -51,7 +53,8 @@ class RecordNotFound < ActiveRecordError ...@@ -51,7 +53,8 @@ class RecordNotFound < ActiveRecordError
class RecordNotSaved < ActiveRecordError class RecordNotSaved < ActiveRecordError
end end
# Raised when SQL statement cannot be executed by the database (for example, it's often the case for MySQL when Ruby driver used is too old). # Raised when SQL statement cannot be executed by the database (for example, it's often the case for
# MySQL when Ruby driver used is too old).
class StatementInvalid < ActiveRecordError class StatementInvalid < ActiveRecordError
end end
...@@ -78,7 +81,8 @@ class RecordNotUnique < WrappedDatabaseException ...@@ -78,7 +81,8 @@ class RecordNotUnique < WrappedDatabaseException
class InvalidForeignKey < WrappedDatabaseException class InvalidForeignKey < WrappedDatabaseException
end end
# Raised when number of bind variables in statement given to <tt>:condition</tt> key (for example, when using +find+ method) # Raised when number of bind variables in statement given to <tt>:condition</tt> key (for example,
# when using +find+ method)
# does not match number of expected variables. # does not match number of expected variables.
# #
# For example, in # For example, in
...@@ -165,4 +169,4 @@ def initialize(errors) ...@@ -165,4 +169,4 @@ def initialize(errors)
@errors = errors @errors = errors
end end
end end
end end
\ No newline at end of file
...@@ -39,9 +39,10 @@ class FixtureClassNotFound < StandardError #:nodoc: ...@@ -39,9 +39,10 @@ class FixtureClassNotFound < StandardError #:nodoc:
# This type of fixture is in YAML format and the preferred default. YAML is a file format which describes data structures # This type of fixture is in YAML format and the preferred default. YAML is a file format which describes data structures
# in a non-verbose, human-readable format. It ships with Ruby 1.8.1+. # in a non-verbose, human-readable format. It ships with Ruby 1.8.1+.
# #
# Unlike single-file fixtures, YAML fixtures are stored in a single file per model, which are placed in the directory appointed # Unlike single-file fixtures, YAML fixtures are stored in a single file per model, which are placed
# by <tt>ActiveSupport::TestCase.fixture_path=(path)</tt> (this is automatically configured for Rails, so you can just # in the directory appointed by <tt>ActiveSupport::TestCase.fixture_path=(path)</tt> (this is
# put your files in <tt><your-rails-app>/test/fixtures/</tt>). The fixture file ends with the <tt>.yml</tt> file extension (Rails example: # automatically configured for Rails, so you can just put your files in <tt><your-rails-app>/test/fixtures/</tt>).
# The fixture file ends with the <tt>.yml</tt> file extension (Rails example:
# <tt><your-rails-app>/test/fixtures/web_sites.yml</tt>). The format of a YAML fixture file looks like this: # <tt><your-rails-app>/test/fixtures/web_sites.yml</tt>). The format of a YAML fixture file looks like this:
# #
# rubyonrails: # rubyonrails:
...@@ -58,7 +59,8 @@ class FixtureClassNotFound < StandardError #:nodoc: ...@@ -58,7 +59,8 @@ class FixtureClassNotFound < StandardError #:nodoc:
# indented list of key/value pairs in the "key: value" format. Records are separated by a blank line for your viewing # indented list of key/value pairs in the "key: value" format. Records are separated by a blank line for your viewing
# pleasure. # pleasure.
# #
# Note that YAML fixtures are unordered. If you want ordered fixtures, use the omap YAML type. See http://yaml.org/type/omap.html # Note that YAML fixtures are unordered. If you want ordered fixtures, use the omap YAML type.
# See http://yaml.org/type/omap.html
# for the specification. You will need ordered fixtures when you have foreign key constraints on keys in the same table. # for the specification. You will need ordered fixtures when you have foreign key constraints on keys in the same table.
# This is commonly needed for tree structures. Example: # This is commonly needed for tree structures. Example:
# #
...@@ -79,7 +81,8 @@ class FixtureClassNotFound < StandardError #:nodoc: ...@@ -79,7 +81,8 @@ class FixtureClassNotFound < StandardError #:nodoc:
# (Rails example: <tt><your-rails-app>/test/fixtures/web_sites.csv</tt>). # (Rails example: <tt><your-rails-app>/test/fixtures/web_sites.csv</tt>).
# #
# The format of this type of fixture file is much more compact than the others, but also a little harder to read by us # The format of this type of fixture file is much more compact than the others, but also a little harder to read by us
# humans. The first line of the CSV file is a comma-separated list of field names. The rest of the file is then comprised # humans. The first line of the CSV file is a comma-separated list of field names. The rest of the
# file is then comprised
# of the actual data (1 per line). Here's an example: # of the actual data (1 per line). Here's an example:
# #
# id, name, url # id, name, url
...@@ -99,15 +102,16 @@ class FixtureClassNotFound < StandardError #:nodoc: ...@@ -99,15 +102,16 @@ class FixtureClassNotFound < StandardError #:nodoc:
# #
# == Single-file fixtures # == Single-file fixtures
# #
# This type of fixture was the original format for Active Record that has since been deprecated in favor of the YAML and CSV formats. # This type of fixture was the original format for Active Record that has since been deprecated in
# Fixtures for this format are created by placing text files in a sub-directory (with the name of the model) to the directory # favor of the YAML and CSV formats.
# appointed by <tt>ActiveSupport::TestCase.fixture_path=(path)</tt> (this is automatically configured for Rails, so you can just # Fixtures for this format are created by placing text files in a sub-directory (with the name of the model)
# put your files in <tt><your-rails-app>/test/fixtures/<your-model-name>/</tt> -- # to the directory appointed by <tt>ActiveSupport::TestCase.fixture_path=(path)</tt> (this is automatically
# configured for Rails, so you can just put your files in <tt><your-rails-app>/test/fixtures/<your-model-name>/</tt> --
# like <tt><your-rails-app>/test/fixtures/web_sites/</tt> for the WebSite model). # like <tt><your-rails-app>/test/fixtures/web_sites/</tt> for the WebSite model).
# #
# Each text file placed in this directory represents a "record". Usually these types of fixtures are named without # Each text file placed in this directory represents a "record". Usually these types of fixtures are named without
# extensions, but if you are on a Windows machine, you might consider adding <tt>.txt</tt> as the extension. Here's what the # extensions, but if you are on a Windows machine, you might consider adding <tt>.txt</tt> as the extension.
# above example might look like: # Here's what the above example might look like:
# #
# web_sites/google # web_sites/google
# web_sites/yahoo.txt # web_sites/yahoo.txt
...@@ -133,7 +137,8 @@ class FixtureClassNotFound < StandardError #:nodoc: ...@@ -133,7 +137,8 @@ class FixtureClassNotFound < StandardError #:nodoc:
# end # end
# end # end
# #
# By default, the <tt>test_helper module</tt> will load all of your fixtures into your test database, so this test will succeed. # By default, the <tt>test_helper module</tt> will load all of your fixtures into your test database,
# so this test will succeed.
# The testing environment will automatically load the all fixtures into the database before each test. # The testing environment will automatically load the all fixtures into the database before each test.
# To ensure consistent data, the environment deletes the fixtures before running the load. # To ensure consistent data, the environment deletes the fixtures before running the load.
# #
...@@ -182,13 +187,15 @@ class FixtureClassNotFound < StandardError #:nodoc: ...@@ -182,13 +187,15 @@ class FixtureClassNotFound < StandardError #:nodoc:
# This will create 1000 very simple YAML fixtures. # This will create 1000 very simple YAML fixtures.
# #
# Using ERb, you can also inject dynamic values into your fixtures with inserts like <tt><%= Date.today.strftime("%Y-%m-%d") %></tt>. # Using ERb, you can also inject dynamic values into your fixtures with inserts like <tt><%= Date.today.strftime("%Y-%m-%d") %></tt>.
# This is however a feature to be used with some caution. The point of fixtures are that they're stable units of predictable # This is however a feature to be used with some caution. The point of fixtures are that they're
# sample data. If you feel that you need to inject dynamic values, then perhaps you should reexamine whether your application # stable units of predictable sample data. If you feel that you need to inject dynamic values, then
# is properly testable. Hence, dynamic values in fixtures are to be considered a code smell. # perhaps you should reexamine whether your application is properly testable. Hence, dynamic values
# in fixtures are to be considered a code smell.
# #
# = Transactional fixtures # = Transactional fixtures
# #
# TestCases can use begin+rollback to isolate their changes to the database instead of having to delete+insert for every test case. # TestCases can use begin+rollback to isolate their changes to the database instead of having to
# delete+insert for every test case.
# #
# class FooTest < ActiveSupport::TestCase # class FooTest < ActiveSupport::TestCase
# self.use_transactional_fixtures = true # self.use_transactional_fixtures = true
...@@ -205,15 +212,18 @@ class FixtureClassNotFound < StandardError #:nodoc: ...@@ -205,15 +212,18 @@ class FixtureClassNotFound < StandardError #:nodoc:
# end # end
# #
# If you preload your test database with all fixture data (probably in the Rakefile task) and use transactional fixtures, # If you preload your test database with all fixture data (probably in the Rakefile task) and use transactional fixtures,
# then you may omit all fixtures declarations in your test cases since all the data's already there and every case rolls back its changes. # then you may omit all fixtures declarations in your test cases since all the data's already there
# and every case rolls back its changes.
# #
# In order to use instantiated fixtures with preloaded data, set +self.pre_loaded_fixtures+ to true. This will provide # In order to use instantiated fixtures with preloaded data, set +self.pre_loaded_fixtures+ to true. This will provide
# access to fixture data for every table that has been loaded through fixtures (depending on the value of +use_instantiated_fixtures+) # access to fixture data for every table that has been loaded through fixtures (depending on the
# value of +use_instantiated_fixtures+)
# #
# When *not* to use transactional fixtures: # When *not* to use transactional fixtures:
# #
# 1. You're testing whether a transaction works correctly. Nested transactions don't commit until all parent transactions commit, # 1. You're testing whether a transaction works correctly. Nested transactions don't commit until
# particularly, the fixtures transaction which is begun in setup and rolled back in teardown. Thus, you won't be able to verify # all parent transactions commit, particularly, the fixtures transaction which is begun in setup
# and rolled back in teardown. Thus, you won't be able to verify
# the results of your transaction until Active Record supports nested transactions or savepoints (in progress). # the results of your transaction until Active Record supports nested transactions or savepoints (in progress).
# 2. Your database does not support transactions. Every Active Record database supports transactions except MySQL MyISAM. # 2. Your database does not support transactions. Every Active Record database supports transactions except MySQL MyISAM.
# Use InnoDB, MaxDB, or NDB instead. # Use InnoDB, MaxDB, or NDB instead.
......
...@@ -48,18 +48,21 @@ def scopes ...@@ -48,18 +48,21 @@ def scopes
# The above calls to <tt>scope</tt> define class methods Shirt.red and Shirt.dry_clean_only. Shirt.red, # The above calls to <tt>scope</tt> define class methods Shirt.red and Shirt.dry_clean_only. Shirt.red,
# in effect, represents the query <tt>Shirt.where(:color => 'red')</tt>. # in effect, represents the query <tt>Shirt.where(:color => 'red')</tt>.
# #
# Unlike <tt>Shirt.find(...)</tt>, however, the object returned by Shirt.red is not an Array; it resembles the association object # Unlike <tt>Shirt.find(...)</tt>, however, the object returned by Shirt.red is not an Array; it
# constructed by a <tt>has_many</tt> declaration. For instance, you can invoke <tt>Shirt.red.first</tt>, <tt>Shirt.red.count</tt>, # resembles the association object constructed by a <tt>has_many</tt> declaration. For instance,
# <tt>Shirt.red.where(:size => 'small')</tt>. Also, just as with the association objects, named \scopes act like an Array, # you can invoke <tt>Shirt.red.first</tt>, <tt>Shirt.red.count</tt>, <tt>Shirt.red.where(:size => 'small')</tt>.
# implementing Enumerable; <tt>Shirt.red.each(&block)</tt>, <tt>Shirt.red.first</tt>, and <tt>Shirt.red.inject(memo, &block)</tt> # Also, just as with the association objects, named \scopes act like an Array, implementing Enumerable;
# <tt>Shirt.red.each(&block)</tt>, <tt>Shirt.red.first</tt>, and <tt>Shirt.red.inject(memo, &block)</tt>
# all behave as if Shirt.red really was an Array. # all behave as if Shirt.red really was an Array.
# #
# These named \scopes are composable. For instance, <tt>Shirt.red.dry_clean_only</tt> will produce all shirts that are both red and dry clean only. # These named \scopes are composable. For instance, <tt>Shirt.red.dry_clean_only</tt> will produce
# Nested finds and calculations also work with these compositions: <tt>Shirt.red.dry_clean_only.count</tt> returns the number of garments # all shirts that are both red and dry clean only.
# for which these criteria obtain. Similarly with <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>. # Nested finds and calculations also work with these compositions: <tt>Shirt.red.dry_clean_only.count</tt>
# returns the number of garments for which these criteria obtain. Similarly with
# <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>.
# #
# All \scopes are available as class methods on the ActiveRecord::Base descendant upon which the \scopes were defined. But they are also available to # All \scopes are available as class methods on the ActiveRecord::Base descendant upon which
# <tt>has_many</tt> associations. If, # the \scopes were defined. But they are also available to <tt>has_many</tt> associations. If,
# #
# class Person < ActiveRecord::Base # class Person < ActiveRecord::Base
# has_many :shirts # has_many :shirts
......
...@@ -67,8 +67,8 @@ module ActiveRecord ...@@ -67,8 +67,8 @@ module ActiveRecord
# #
# == Configuration # == Configuration
# #
# In order to activate an observer, list it in the <tt>config.active_record.observers</tt> configuration setting in your # In order to activate an observer, list it in the <tt>config.active_record.observers</tt> configuration
# <tt>config/application.rb</tt> file. # setting in your <tt>config/application.rb</tt> file.
# #
# config.active_record.observers = :comment_observer, :signup_observer # config.active_record.observers = :comment_observer, :signup_observer
# #
......
...@@ -91,8 +91,8 @@ def destroy ...@@ -91,8 +91,8 @@ def destroy
# like render <tt>:partial => @client.becomes(Company)</tt> to render that # like render <tt>:partial => @client.becomes(Company)</tt> to render that
# instance using the companies/company partial instead of clients/client. # instance using the companies/company partial instead of clients/client.
# #
# Note: The new instance will share a link to the same attributes as the original class. So any change to the attributes in either # Note: The new instance will share a link to the same attributes as the original class.
# instance will affect the other. # So any change to the attributes in either instance will affect the other.
def becomes(klass) def becomes(klass)
became = klass.new became = klass.new
became.instance_variable_set("@attributes", @attributes) became.instance_variable_set("@attributes", @attributes)
......
...@@ -5,26 +5,33 @@ module Calculations ...@@ -5,26 +5,33 @@ module Calculations
# Count operates using three different approaches. # Count operates using three different approaches.
# #
# * Count all: By not passing any parameters to count, it will return a count of all the rows for the model. # * Count all: By not passing any parameters to count, it will return a count of all the rows for the model.
# * Count using column: By passing a column name to count, it will return a count of all the rows for the model with supplied column present # * Count using column: By passing a column name to count, it will return a count of all the
# rows for the model with supplied column present
# * Count using options will find the row count matched by the options used. # * Count using options will find the row count matched by the options used.
# #
# The third approach, count using options, accepts an option hash as the only parameter. The options are: # The third approach, count using options, accepts an option hash as the only parameter. The options are:
# #
# * <tt>:conditions</tt>: An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. See conditions in the intro to ActiveRecord::Base. # * <tt>:conditions</tt>: An SQL fragment like "administrator = 1" or [ "user_name = ?", username ].
# See conditions in the intro to ActiveRecord::Base.
# * <tt>:joins</tt>: Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed) # * <tt>:joins</tt>: Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed)
# or named associations in the same form used for the <tt>:include</tt> option, which will perform an INNER JOIN on the associated table(s). # or named associations in the same form used for the <tt>:include</tt> option, which will
# If the value is a string, then the records will be returned read-only since they will have attributes that do not correspond to the table's columns. # perform an INNER JOIN on the associated table(s).
# If the value is a string, then the records will be returned read-only since they will have
# attributes that do not correspond to the table's columns.
# Pass <tt>:readonly => false</tt> to override. # Pass <tt>:readonly => false</tt> to override.
# * <tt>:include</tt>: Named associations that should be loaded alongside using LEFT OUTER JOINs. The symbols named refer # * <tt>:include</tt>: Named associations that should be loaded alongside using LEFT OUTER JOINs.
# to already defined associations. When using named associations, count returns the number of DISTINCT items for the model you're counting. # The symbols named refer to already defined associations. When using named associations, count
# returns the number of DISTINCT items for the model you're counting.
# See eager loading under Associations. # See eager loading under Associations.
# * <tt>:order</tt>: An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations). # * <tt>:order</tt>: An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations).
# * <tt>:group</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause. # * <tt>:group</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
# * <tt>:select</tt>: By default, this is * as in SELECT * FROM, but can be changed if you, for example, want to do a join but not # * <tt>:select</tt>: By default, this is * as in SELECT * FROM, but can be changed if you, for example,
# want to do a join but not
# include the joined columns. # include the joined columns.
# * <tt>:distinct</tt>: Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) ... # * <tt>:distinct</tt>: Set this to true to make this a distinct calculation, such as
# * <tt>:from</tt> - By default, this is the table name of the class, but can be changed to an alternate table name (or even the name # SELECT COUNT(DISTINCT posts.id) ...
# of a database view). # * <tt>:from</tt> - By default, this is the table name of the class, but can be changed to an
# alternate table name (or even the name of a database view).
# #
# Examples for counting all: # Examples for counting all:
# Person.count # returns the total count of all people # Person.count # returns the total count of all people
...@@ -34,12 +41,19 @@ module Calculations ...@@ -34,12 +41,19 @@ module Calculations
# #
# Examples for count with options: # Examples for count with options:
# Person.count(:conditions => "age > 26") # Person.count(:conditions => "age > 26")
# Person.count(:conditions => "age > 26 AND job.salary > 60000", :include => :job) # because of the named association, it finds the DISTINCT count using LEFT OUTER JOIN. #
# Person.count(:conditions => "age > 26 AND job.salary > 60000", :joins => "LEFT JOIN jobs on jobs.person_id = person.id") # finds the number of rows matching the conditions and joins. # # because of the named association, it finds the DISTINCT count using LEFT OUTER JOIN.
# Person.count(:conditions => "age > 26 AND job.salary > 60000", :include => :job)
#
# # finds the number of rows matching the conditions and joins.
# Person.count(:conditions => "age > 26 AND job.salary > 60000",
# :joins => "LEFT JOIN jobs on jobs.person_id = person.id")
#
# Person.count('id', :conditions => "age > 26") # Performs a COUNT(id) # Person.count('id', :conditions => "age > 26") # Performs a COUNT(id)
# Person.count(:all, :conditions => "age > 26") # Performs a COUNT(*) (:all is an alias for '*') # Person.count(:all, :conditions => "age > 26") # Performs a COUNT(*) (:all is an alias for '*')
# #
# Note: <tt>Person.count(:all)</tt> will not work because it will use <tt>:all</tt> as the condition. Use Person.count instead. # Note: <tt>Person.count(:all)</tt> will not work because it will use <tt>:all</tt> as the condition.
# Use Person.count instead.
def count(column_name = nil, options = {}) def count(column_name = nil, options = {})
column_name, options = nil, column_name if column_name.is_a?(Hash) column_name, options = nil, column_name if column_name.is_a?(Hash)
calculate(:count, column_name, options) calculate(:count, column_name, options)
...@@ -80,13 +94,15 @@ def sum(column_name, options = {}) ...@@ -80,13 +94,15 @@ def sum(column_name, options = {})
calculate(:sum, column_name, options) calculate(:sum, column_name, options)
end end
# This calculates aggregate values in the given column. Methods for count, sum, average, minimum, and maximum have been added as shortcuts. # This calculates aggregate values in the given column. Methods for count, sum, average,
# Options such as <tt>:conditions</tt>, <tt>:order</tt>, <tt>:group</tt>, <tt>:having</tt>, and <tt>:joins</tt> can be passed to customize the query. # minimum, and maximum have been added as shortcuts. Options such as <tt>:conditions</tt>,
# <tt>:order</tt>, <tt>:group</tt>, <tt>:having</tt>, and <tt>:joins</tt> can be passed to customize the query.
# #
# There are two basic forms of output: # There are two basic forms of output:
# * Single aggregate value: The single value is type cast to Fixnum for COUNT, Float for AVG, and the given column's type for everything else. # * Single aggregate value: The single value is type cast to Fixnum for COUNT, Float
# * Grouped values: This returns an ordered hash of the values and groups them by the <tt>:group</tt> option. It takes either a column name, or the name # for AVG, and the given column's type for everything else.
# of a belongs_to association. # * Grouped values: This returns an ordered hash of the values and groups them by the
# <tt>:group</tt> option. It takes either a column name, or the name of a belongs_to association.
# #
# values = Person.maximum(:age, :group => 'last_name') # values = Person.maximum(:age, :group => 'last_name')
# puts values["Drake"] # puts values["Drake"]
...@@ -102,21 +118,30 @@ def sum(column_name, options = {}) ...@@ -102,21 +118,30 @@ def sum(column_name, options = {})
# end # end
# #
# Options: # Options:
# * <tt>:conditions</tt> - An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. See conditions in the intro to ActiveRecord::Base. # * <tt>:conditions</tt> - An SQL fragment like "administrator = 1" or [ "user_name = ?", username ].
# * <tt>:include</tt>: Eager loading, see Associations for details. Since calculations don't load anything, the purpose of this is to access fields on joined tables in your conditions, order, or group clauses. # See conditions in the intro to ActiveRecord::Base.
# * <tt>:joins</tt> - An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id". (Rarely needed). # * <tt>:include</tt>: Eager loading, see Associations for details. Since calculations don't load anything,
# The records will be returned read-only since they will have attributes that do not correspond to the table's columns. # the purpose of this is to access fields on joined tables in your conditions, order, or group clauses.
# * <tt>:joins</tt> - An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id".
# (Rarely needed).
# The records will be returned read-only since they will have attributes that do not correspond to the
# table's columns.
# * <tt>:order</tt> - An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations). # * <tt>:order</tt> - An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations).
# * <tt>:group</tt> - An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause. # * <tt>:group</tt> - An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
# * <tt>:select</tt> - By default, this is * as in SELECT * FROM, but can be changed if you for example want to do a join, but not # * <tt>:select</tt> - By default, this is * as in SELECT * FROM, but can be changed if you for example
# include the joined columns. # want to do a join, but not include the joined columns.
# * <tt>:distinct</tt> - Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) ... # * <tt>:distinct</tt> - Set this to true to make this a distinct calculation, such as
# SELECT COUNT(DISTINCT posts.id) ...
# #
# Examples: # Examples:
# Person.calculate(:count, :all) # The same as Person.count # Person.calculate(:count, :all) # The same as Person.count
# Person.average(:age) # SELECT AVG(age) FROM people... # Person.average(:age) # SELECT AVG(age) FROM people...
# Person.minimum(:age, :conditions => ['last_name != ?', 'Drake']) # Selects the minimum age for everyone with a last name other than 'Drake' # Person.minimum(:age, :conditions => ['last_name != ?', 'Drake']) # Selects the minimum age for
# Person.minimum(:age, :having => 'min(age) > 17', :group => :last_name) # Selects the minimum age for any family without any minors # # everyone with a last name other than 'Drake'
#
# # Selects the minimum age for any family without any minors
# Person.minimum(:age, :having => 'min(age) > 17', :group => :last_name)
#
# Person.sum("2 * age") # Person.sum("2 * age")
def calculate(operation, column_name, options = {}) def calculate(operation, column_name, options = {})
if options.except(:distinct).present? if options.except(:distinct).present?
......
...@@ -21,23 +21,28 @@ module FinderMethods ...@@ -21,23 +21,28 @@ module FinderMethods
# #
# ==== Parameters # ==== Parameters
# #
# * <tt>:conditions</tt> - An SQL fragment like "administrator = 1", <tt>[ "user_name = ?", username ]</tt>, or <tt>["user_name = :user_name", { :user_name => user_name }]</tt>. See conditions in the intro. # * <tt>:conditions</tt> - An SQL fragment like "administrator = 1", <tt>[ "user_name = ?", username ]</tt>,
# or <tt>["user_name = :user_name", { :user_name => user_name }]</tt>. See conditions in the intro.
# * <tt>:order</tt> - An SQL fragment like "created_at DESC, name". # * <tt>:order</tt> - An SQL fragment like "created_at DESC, name".
# * <tt>:group</tt> - An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause. # * <tt>:group</tt> - An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
# * <tt>:having</tt> - Combined with +:group+ this can be used to filter the records that a <tt>GROUP BY</tt> returns. Uses the <tt>HAVING</tt> SQL-clause. # * <tt>:having</tt> - Combined with +:group+ this can be used to filter the records that a
# <tt>GROUP BY</tt> returns. Uses the <tt>HAVING</tt> SQL-clause.
# * <tt>:limit</tt> - An integer determining the limit on the number of rows that should be returned. # * <tt>:limit</tt> - An integer determining the limit on the number of rows that should be returned.
# * <tt>:offset</tt> - An integer determining the offset from where the rows should be fetched. So at 5, it would skip rows 0 through 4. # * <tt>:offset</tt> - An integer determining the offset from where the rows should be fetched. So at 5,
# it would skip rows 0 through 4.
# * <tt>:joins</tt> - Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed), # * <tt>:joins</tt> - Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed),
# named associations in the same form used for the <tt>:include</tt> option, which will perform an <tt>INNER JOIN</tt> on the associated table(s), # named associations in the same form used for the <tt>:include</tt> option, which will perform an
# <tt>INNER JOIN</tt> on the associated table(s),
# or an array containing a mixture of both strings and named associations. # or an array containing a mixture of both strings and named associations.
# If the value is a string, then the records will be returned read-only since they will have attributes that do not correspond to the table's columns. # If the value is a string, then the records will be returned read-only since they will
# have attributes that do not correspond to the table's columns.
# Pass <tt>:readonly => false</tt> to override. # Pass <tt>:readonly => false</tt> to override.
# * <tt>:include</tt> - Names associations that should be loaded alongside. The symbols named refer # * <tt>:include</tt> - Names associations that should be loaded alongside. The symbols named refer
# to already defined associations. See eager loading under Associations. # to already defined associations. See eager loading under Associations.
# * <tt>:select</tt> - By default, this is "*" as in "SELECT * FROM", but can be changed if you, for example, want to do a join but not # * <tt>:select</tt> - By default, this is "*" as in "SELECT * FROM", but can be changed if you,
# include the joined columns. Takes a string with the SELECT SQL fragment (e.g. "id, name"). # for example, want to do a join but not include the joined columns. Takes a string with the SELECT SQL fragment (e.g. "id, name").
# * <tt>:from</tt> - By default, this is the table name of the class, but can be changed to an alternate table name (or even the name # * <tt>:from</tt> - By default, this is the table name of the class, but can be changed
# of a database view). # to an alternate table name (or even the name of a database view).
# * <tt>:readonly</tt> - Mark the returned records read-only so they cannot be saved or updated. # * <tt>:readonly</tt> - Mark the returned records read-only so they cannot be saved or updated.
# * <tt>:lock</tt> - An SQL fragment like "FOR UPDATE" or "LOCK IN SHARE MODE". # * <tt>:lock</tt> - An SQL fragment like "FOR UPDATE" or "LOCK IN SHARE MODE".
# <tt>:lock => true</tt> gives connection's default exclusive lock, usually "FOR UPDATE". # <tt>:lock => true</tt> gives connection's default exclusive lock, usually "FOR UPDATE".
......
...@@ -21,7 +21,8 @@ module ActiveRecord ...@@ -21,7 +21,8 @@ module ActiveRecord
# #
# This feature can easily be turned off by assigning value <tt>false</tt> . # This feature can easily be turned off by assigning value <tt>false</tt> .
# #
# If your attributes are time zone aware and you desire to skip time zone conversion for certain attributes then you can do following: # If your attributes are time zone aware and you desire to skip time zone conversion for certain
# attributes then you can do following:
# #
# Topic.skip_time_zone_conversion_for_attributes = [:written_on] # Topic.skip_time_zone_conversion_for_attributes = [:written_on]
module Timestamp module Timestamp
......
...@@ -27,8 +27,9 @@ module ClassMethods ...@@ -27,8 +27,9 @@ module ClassMethods
# #
# this would specify a circular dependency and cause infinite recursion. # this would specify a circular dependency and cause infinite recursion.
# #
# NOTE: This validation will not fail if the association hasn't been assigned. If you want to ensure that the association # NOTE: This validation will not fail if the association hasn't been assigned. If you want to
# is both present and guaranteed to be valid, you also need to use +validates_presence_of+. # ensure that the association is both present and guaranteed to be valid, you also need to
# use +validates_presence_of+.
# #
# Configuration options: # Configuration options:
# * <tt>:message</tt> - A custom error message (default is: "is invalid") # * <tt>:message</tt> - A custom error message (default is: "is invalid")
...@@ -44,4 +45,4 @@ def validates_associated(*attr_names) ...@@ -44,4 +45,4 @@ def validates_associated(*attr_names)
end end
end end
end end
end end
\ No newline at end of file
...@@ -78,22 +78,25 @@ def mount_sql_and_params(klass, table_name, attribute, value) #:nodoc: ...@@ -78,22 +78,25 @@ def mount_sql_and_params(klass, table_name, attribute, value) #:nodoc:
end end
module ClassMethods module ClassMethods
# Validates whether the value of the specified attributes are unique across the system. Useful for making sure that only one user # Validates whether the value of the specified attributes are unique across the system.
# Useful for making sure that only one user
# can be named "davidhh". # can be named "davidhh".
# #
# class Person < ActiveRecord::Base # class Person < ActiveRecord::Base
# validates_uniqueness_of :user_name, :scope => :account_id # validates_uniqueness_of :user_name, :scope => :account_id
# end # end
# #
# It can also validate whether the value of the specified attributes are unique based on multiple scope parameters. For example, # It can also validate whether the value of the specified attributes are unique based on multiple
# making sure that a teacher can only be on the schedule once per semester for a particular class. # scope parameters. For example, making sure that a teacher can only be on the schedule once
# per semester for a particular class.
# #
# class TeacherSchedule < ActiveRecord::Base # class TeacherSchedule < ActiveRecord::Base
# validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id] # validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
# end # end
# #
# When the record is created, a check is performed to make sure that no record exists in the database with the given value for the specified # When the record is created, a check is performed to make sure that no record exists in the database
# attribute (that maps to a column). When the record is updated, the same check is made but disregarding the record itself. # with the given value for the specified attribute (that maps to a column). When the record is updated,
# the same check is made but disregarding the record itself.
# #
# Configuration options: # Configuration options:
# * <tt>:message</tt> - Specifies a custom error message (default is: "has already been taken"). # * <tt>:message</tt> - Specifies a custom error message (default is: "has already been taken").
...@@ -102,11 +105,12 @@ module ClassMethods ...@@ -102,11 +105,12 @@ module ClassMethods
# * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+). # * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+). # * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).
# method, proc or string should return or evaluate to a true or false value. # The method, proc or string should return or evaluate to a true or false value.
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The # not occur (e.g. <tt>:unless => :skip_validation</tt>, or
# method, proc or string should return or evaluate to a true or false value. # <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The method, proc or string should
# return or evaluate to a true or false value.
# #
# === Concurrency and integrity # === Concurrency and integrity
# #
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册