Class: ActiveRecord::Base
- Inherits:
-
Object
- Object
- ActiveRecord::Base
- Includes:
- ClassInheritableAttributes
- Defined in:
- lib/active_record/base.rb,
lib/active_record/locking.rb,
lib/active_record/timestamp.rb,
lib/active_record/deprecated_finders.rb,
lib/active_record/connection_adapters/mysql_adapter.rb,
lib/active_record/connection_adapters/sqlite_adapter.rb,
lib/active_record/connection_adapters/abstract_adapter.rb,
lib/active_record/connection_adapters/postgresql_adapter.rb
Overview
Active Record objects doesn’t specify their attributes directly, but rather infer them from the table definition with which they’re linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.
See the mapping rules in table_name and the full example in files/README.html for more insight.
Creation
Active Records accepts constructor parameters either in a hash or as a block. The hash method is especially useful when you’re receiving the data from somewhere else, like a HTTP request. It works like this:
user = User.new(:name => "David", :occupation => "Code Artist")
user.name # => "David"
You can also use block initialization:
user = User.new do |u|
u.name = "David"
u.occupation = "Code Artist"
end
And of course you can just create a bare object and specify the attributes after the fact:
user = User.new
user.name = "David"
user.occupation = "Code Artist"
Conditions
Conditions can either be specified as a string or an array representing the WHERE-part of an SQL statement. The array form is to be used when the condition input is tainted and requires sanitization. The string form can be used for statements that doesn’t involve tainted data. Examples:
User < ActiveRecord::Base
def self.authenticate_unsafely(user_name, password)
find_first("user_name = '#{user_name}' AND password = '#{password}'")
end
def self.authenticate_safely(user_name, password)
find_first([ "user_name = ? AND password = ?", user_name, password ])
end
end
The authenticate_unsafely
method inserts the parameters directly into the query and is thus susceptible to SQL-injection attacks if the user_name
and password
parameters come directly from a HTTP request. The authenticate_safely
method, on the other hand, will sanitize the user_name
and password
before inserting them in the query, which will ensure that an attacker can’t escape the query and fake the login (or worse).
When using multiple parameters in the conditions, it can easily become hard to read exactly what the fourth or fifth question mark is supposed to represent. In those cases, you can resort to named bind variables instead. That’s done by replacing the question marks with symbols and supplying a hash with values for the matching symbol keys:
Company.find(:first, [
"id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
{ :id => 3, :name => "37signals", :division => "First", :accounting_date => '2005-01-01' }
])
Overwriting default accessors
All column values are automatically available through basic accessors on the Active Record object, but some times you want to specialize this behavior. This can be done by either by overwriting the default accessors (using the same name as the attribute) calling read_attribute(attr_name) and write_attribute(attr_name, value) to actually change things. Example:
class Song < ActiveRecord::Base
# Uses an integer of seconds to hold the length of the song
def length=(minutes)
write_attribute(:length, minutes * 60)
end
def length
read_attribute(:length) / 60
end
end
You can alternatively use self=(value) and self instead of write_attribute(:attribute, vaule) and read_attribute(:attribute) as a shorter form.
Accessing attributes before they have been type casted
Some times you want to be able to read the raw attribute data without having the column-determined type cast run its course first. That can be done by using the <attribute>_before_type_cast accessors that all attributes have. For example, if your Account model has a balance attribute, you can call account.balance_before_type_cast or account.id_before_type_cast.
This is especially useful in validation situations where the user might supply a string for an integer field and you want to display the original string back in an error message. Accessing the attribute normally would type cast the string to 0, which isn’t what you want.
Dynamic attribute-based finders
Dynamic attribute-based finders are a cleaner way of getting objects by simple queries without turning to SQL. They work by appending the name of an attribute to find_by_
, so you get finders like Person.find_by_user_name, Payment.find_by_transaction_id
. So instead of writing Person.find(:first, ["user_name = ?", user_name])
, you just do Person.find_by_user_name(user_name)
.
It’s also possible to use multiple attributes in the same find by separating them with “and”, so you get finders like Person.find_by_user_name_and_password
or even Payment.find_by_purchaser_and_state_and_country
. So instead of writing Person.find(:first, ["user_name = ? AND password = ?", user_name, password])
, you just do Person.find_by_user_name_and_password(user_name, password)
.
It’s even possible to use all the additional parameters to find. For example, the full interface for Payment.find_all_by_amount is actually Payment.find_all_by_amount(amount, options). And the full interface to Person.find_by_user_name is actually Person.find_by_user_name(user_name, options). So you could call Payment.find_all_by_amount(50, :order => "created_on")
.
Saving arrays, hashes, and other non-mappable objects in text columns
Active Record can serialize any object in text columns using YAML. To do so, you must specify this with a call to the class method serialize
. This makes it possible to store arrays, hashes, and other non-mappeable objects without doing any additional work. Example:
class User < ActiveRecord::Base
serialize :preferences
end
user = User.create(:preferences) => { "background" => "black", "display" => large })
User.find(user.id).preferences # => { "background" => "black", "display" => large }
You can also specify an class option as the second parameter that’ll raise an exception if a serialized object is retrieved as a descendent of a class not in the hierarchy. Example:
class User < ActiveRecord::Base
serialize :preferences, Hash
end
user = User.create(:preferences => %w( one two three ))
User.find(user.id).preferences # raises SerializationTypeMismatch
Single table inheritance
Active Record allows inheritance by storing the name of the class in a column that by default is called “type” (can be changed by overwriting Base.inheritance_column
). This means that an inheritance looking like this:
class Company < ActiveRecord::Base; end
class Firm < Company; end
class Client < Company; end
class PriorityClient < Client; end
When you do Firm.create(:name => “37signals”), this record will be saved in the companies table with type = “Firm”. You can then fetch this row again using Company.find(:first, “name = ‘37signals’”) and it will return a Firm object.
If you don’t have a type column defined in your table, single-table inheritance won’t be triggered. In that case, it’ll work just like normal subclasses with no special magic for differentiating between them or reloading the right type with find.
Note, all the attributes for all the cases are kept in the same table. Read more: www.martinfowler.com/eaaCatalog/singleTableInheritance.html
Connection to multiple databases in different models
Connections are usually created through ActiveRecord::Base.establish_connection and retrieved by ActiveRecord::Base.connection. All classes inheriting from ActiveRecord::Base will use this connection. But you can also set a class-specific connection. For example, if Course is a ActiveRecord::Base, but resides in a different database you can just say Course.establish_connection and Course *and all its subclasses* will use this connection instead.
This feature is implemented by keeping a connection pool in ActiveRecord::Base that is a Hash indexed by the class. If a connection is requested, the retrieve_connection method will go up the class-hierarchy until a connection is found in the connection pool.
Exceptions
-
ActiveRecordError
– generic error class and superclass of all other errors raised by Active Record -
AdapterNotSpecified
– the configuration hash used inestablish_connection
didn’t include a:adapter
key. -
AdapterNotSpecified
– the:adapter
key used inestablish_connection
specified an non-existent adapter (or a bad spelling of an existing one). -
AssociationTypeMismatch
– the object assigned to the association wasn’t of the type specified in the association definition. -
SerializationTypeMismatch
– the object serialized wasn’t of the class specified as the second parameter. -
ConnectionNotEstablished
– no connection has been established. Useestablish_connection
before querying. -
RecordNotFound
– no record responded to the find* method. Either the row with the given ID doesn’t exist or the row didn’t meet the additional restrictions. -
StatementInvalid
– the database server rejected the SQL statement. The precise error is added in the message. Either the record with the given ID doesn’t exist or the record didn’t meet the additional restrictions. -
MultiparameterAssignmentErrors
– collection of errors that occurred during a mass assignment using theattributes=
method. Theerrors
property of this exception contains an array ofAttributeAssignmentError
objects that should be inspected to determine which attributes triggered the errors. -
AttributeAssignmentError
– an error occurred while doing a mass assignment through theattributes=
method. You can inspect theattribute
property of the exception object to determine which attribute triggered the error.
Note: The attributes listed are class-level attributes (accessible from both the class and instance level). So it’s possible to assign a logger to the class through Base.logger= which will then be used by all instances in the current object space.
Defined Under Namespace
Classes: ConnectionSpecification
Constant Summary collapse
- @@subclasses =
{}
- @@primary_key_prefix_type =
nil
- @@table_name_prefix =
""
- @@table_name_suffix =
""
- @@pluralize_table_names =
true
- @@colorize_logging =
true
- @@default_timezone =
:local
- @@lock_optimistically =
true
- @@record_timestamps =
Records the creation date and possibly time in created_on (date only) or created_at (date and time) and the update date and possibly time in updated_on and updated_at. This only happens if the object responds to either of these messages, which they will do automatically if the table has columns of either of these names. This feature is turned on by default.
true
- @@timestamps_gmt =
deprecated: use ActiveRecord::Base.default_timezone instead.
false
- @@defined_connections =
The class -> [adapter_method, config] map
{}
Class Method Summary collapse
-
.===(object) ⇒ Object
Overwrite the default class equality method to provide support for association proxies.
-
.accessible_attributes ⇒ Object
Returns an array of all the attributes that have been made accessible to mass-assignment.
-
.attr_accessible(*attributes) ⇒ Object
If this macro is used, only those attributed named in it will be accessible for mass-assignment, such as
new(attributes)
andattributes=(attributes)
. -
.attr_protected(*attributes) ⇒ Object
Attributes named in this macro are protected from mass-assignment, such as
new(attributes)
andattributes=(attributes)
. -
.benchmark(title) ⇒ Object
Used to aggregate logging and benchmark, so you can measure and represent multiple statements in a single block.
-
.class_name(table_name = table_name) ⇒ Object
Turns the
table_name
back into a class name following the reverse rules oftable_name
. -
.column_methods_hash ⇒ Object
Returns a hash of all the methods added to query each of the columns in the table with the name of the method as the key and true as the value.
- .column_names ⇒ Object
-
.columns ⇒ Object
Returns an array of column objects for the table associated with this class.
-
.columns_hash ⇒ Object
Returns an array of column objects for the table associated with this class.
-
.connected? ⇒ Boolean
Returns true if a connection that’s accessible to this class have already been opened.
-
.connection ⇒ Object
Returns the connection currently associated with the class.
-
.connection=(spec) ⇒ Object
Set the connection for the class.
-
.content_columns ⇒ Object
Returns an array of columns objects where the primary id, all columns ending in “_id” or “_count”, and columns used for single table inheritance has been removed.
-
.count(conditions = nil, joins = nil) ⇒ Object
Returns the number of records that meets the
conditions
. -
.count_by_sql(sql) ⇒ Object
Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part.
-
.create(attributes = nil) ⇒ Object
Creates an object, instantly saves it as a record (if the validation permits it), and returns it.
-
.decrement_counter(counter_name, id) ⇒ Object
Works like increment_counter, but decrements instead.
-
.delete(id) ⇒ Object
Deletes the record with the given
id
without instantiating an object first. -
.delete_all(conditions = nil) ⇒ Object
Deletes all the records that matches the
condition
without instantiating the objects first (and hence not calling the destroy method). -
.descends_from_active_record? ⇒ Boolean
:nodoc:.
-
.destroy(id) ⇒ Object
Destroys the record with the given
id
by instantiating the object and calling #destroy (all the callbacks are the triggered). -
.destroy_all(conditions = nil) ⇒ Object
Destroys the objects for all the records that matches the
condition
by instantiating each object and calling the destroy method. -
.establish_connection(spec = nil) ⇒ Object
Establishes the connection to the database.
-
.exists?(id) ⇒ Boolean
Returns true if the given
id
represents the primary key of a record in the database, false otherwise. -
.find(*args) ⇒ Object
Find operates with three different retreval approaches:.
-
.find_all(conditions = nil, orderings = nil, limit = nil, joins = nil) ⇒ Object
This method is deprecated in favor of find(:all, options).
-
.find_by_sql(sql) ⇒ Object
Works like find_all, but requires a complete SQL string.
-
.find_first(conditions = nil, orderings = nil, joins = nil) ⇒ Object
This method is deprecated in favor of find(:first, options).
-
.find_on_conditions(ids, conditions) ⇒ Object
This method is deprecated in favor of find with the :conditions option.
-
.human_attribute_name(attribute_key_name) ⇒ Object
Transforms attribute key names into a more humane format, such as “First name” instead of “first_name”.
-
.increment_counter(counter_name, id) ⇒ Object
Increments the specified counter by one.
-
.inheritance_column ⇒ Object
Defines the column name for use with single table inheritance – can be overridden in subclasses.
-
.inherited(child) ⇒ Object
:nodoc:.
-
.mysql_connection(config) ⇒ Object
Establishes a connection to the database that’s used by all Active Record objects.
-
.postgresql_connection(config) ⇒ Object
Establishes a connection to the database that’s used by all Active Record objects.
-
.primary_key ⇒ Object
Defines the primary key field – can be overridden in subclasses.
-
.protected_attributes ⇒ Object
Returns an array of all the attributes that have been protected from mass-assignment.
-
.quote(object) ⇒ Object
:nodoc:.
-
.remove_connection(klass = self) ⇒ Object
Remove the connection for this class.
-
.reset_column_information ⇒ Object
Resets all the cached information about columns, which will cause they to be reloaded on the next request.
-
.reset_column_information_and_inheritable_attributes_for_all_subclasses ⇒ Object
:nodoc:.
-
.retrieve_connection ⇒ Object
Locate the connection of the nearest super class.
-
.sanitize(object) ⇒ Object
Used to sanitize objects before they’re used in an SELECT SQL-statement.
-
.serialize(attr_name, class_name = Object) ⇒ Object
Specifies that the attribute by the name of
attr_name
should be serialized before saving to the database and unserialized after loading from the database. -
.serialized_attributes ⇒ Object
Returns a hash of all the attributes that have been specified for serialization as keys and their class restriction as values.
-
.set_inheritance_column(value = nil, &block) ⇒ Object
(also: inheritance_column=)
Sets the name of the inheritance column to use to the given value, or (if the value # is nil or false) to the value returned by the given block.
-
.set_primary_key(value = nil, &block) ⇒ Object
(also: primary_key=)
Sets the name of the primary key column to use to the given value, or (if the value is nil or false) to the value returned by the given block.
-
.set_table_name(value = nil, &block) ⇒ Object
(also: table_name=)
Sets the table name to use to the given value, or (if the value is nil or false) to the value returned by the given block.
-
.silence ⇒ Object
Silences the logger for the duration of the block.
-
.sqlite3_connection(config) ⇒ Object
sqlite3 adapter reuses sqlite_connection.
-
.sqlite_connection(config) ⇒ Object
Establishes a connection to the database that’s used by all Active Record objects.
-
.symbolize_strings_in_hash(hash) ⇒ Object
Converts all strings in a hash to symbols.
-
.table_name ⇒ Object
Guesses the table name (in forced lower-case) based on the name of the class in the inheritance hierarchy descending directly from ActiveRecord.
-
.timestamps_gmt ⇒ Object
:nodoc:.
-
.timestamps_gmt=(gmt) ⇒ Object
:nodoc:.
-
.update(id, attributes) ⇒ Object
Finds the record from the passed
id
, instantly saves it with the passedattributes
(if the validation permits it), and returns it. -
.update_all(updates, conditions = nil) ⇒ Object
Updates all records with the SET-part of an SQL update statement in
updates
and returns an integer with the number of rows updates.
Instance Method Summary collapse
-
#==(comparison_object) ⇒ Object
Returns true if the
comparison_object
is the same object, or is of the same type and has the same id. -
#[](attr_name) ⇒ Object
Returns the value of attribute identified by
attr_name
after it has been type cast (for example, “2004-12-12” in a data column is cast to a date object, like Date.new(2004, 12, 12)). -
#[]=(attr_name, value) ⇒ Object
Updates the attribute identified by
attr_name
with the specifiedvalue
. -
#attribute_names ⇒ Object
Returns an array of names for the attributes available on this object sorted alphabetically.
-
#attribute_present?(attribute) ⇒ Boolean
Returns true if the specified
attribute
has been set by the user or by a database load and is neither nil nor empty? (the latter only applies to objects that responds to empty?, most notably Strings). -
#attributes ⇒ Object
Returns a hash of all the attributes with their names as keys and clones of their objects as values.
-
#attributes=(attributes) ⇒ Object
Allows you to set all the attributes at once by passing in a hash with keys matching the attribute names (which again matches the column names).
-
#clone ⇒ Object
Returns a clone of the record that hasn’t been assigned an id yet and is treated as a new record.
-
#column_for_attribute(name) ⇒ Object
Returns the column object for the named attribute.
-
#connection ⇒ Object
Returns the connection currently associated with the class.
-
#decrement(attribute) ⇒ Object
Initializes the
attribute
to zero if nil and subtracts one. -
#decrement!(attribute) ⇒ Object
Decrements the
attribute
and saves the record. -
#destroy ⇒ Object
Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can’t be persisted).
-
#eql?(comparison_object) ⇒ Boolean
Delegates to ==.
-
#hash ⇒ Object
Delegates to id in order to allow two records of the same type and id to work with something like: [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ].
-
#id ⇒ Object
(also: #to_param)
Every Active Record class must use “id” as their primary ID.
-
#id=(value) ⇒ Object
Sets the primary ID.
-
#id_before_type_cast ⇒ Object
:nodoc:.
-
#increment(attribute) ⇒ Object
Initializes the
attribute
to zero if nil and adds one. -
#increment!(attribute) ⇒ Object
Increments the
attribute
and saves the record. -
#initialize(attributes = nil) {|_self| ... } ⇒ Base
constructor
New objects can be instantiated as either empty (pass no construction parameter) or pre-set with attributes but not yet saved (pass a hash with key names matching the associated table column names).
-
#locking_enabled? ⇒ Boolean
:nodoc:.
-
#new_record? ⇒ Boolean
Returns true if this object hasn’t been saved yet – that is, a record for the object doesn’t exist yet.
-
#quoted_id ⇒ Object
:nodoc:.
-
#reload ⇒ Object
Reloads the attributes of this object from the database.
-
#respond_to?(method, include_priv = false) ⇒ Boolean
A Person object with a name attribute can ask person.respond_to?(“name”), person.respond_to?(“name=”), and person.respond_to?(“name?”) which will all return true.
-
#respond_to_without_attributes? ⇒ Object
For checking respond_to? without searching the attributes (which is faster).
-
#save ⇒ Object
-
No record exists: Creates a new record with values matching those of the object attributes.
-
-
#toggle(attribute) ⇒ Object
Turns an
attribute
that’s currently true into false and vice versa. -
#toggle!(attribute) ⇒ Object
Toggles the
attribute
and saves the record. -
#update_attribute(name, value) ⇒ Object
Updates a single attribute and saves the record.
-
#update_attributes(attributes) ⇒ Object
Updates all the attributes in from the passed hash and saves the record.
Constructor Details
#initialize(attributes = nil) {|_self| ... } ⇒ Base
New objects can be instantiated as either empty (pass no construction parameter) or pre-set with attributes but not yet saved (pass a hash with key names matching the associated table column names). In both instances, valid attribute keys are determined by the column names of the associated table – hence you can’t have attributes that aren’t part of the table columns.
921 922 923 924 925 926 927 |
# File 'lib/active_record/base.rb', line 921 def initialize(attributes = nil) @attributes = attributes_from_column_definition @new_record = true ensure_proper_type self.attributes = attributes unless attributes.nil? yield self if block_given? end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method_id, *arguments) ⇒ Object (private)
Allows access to the object attributes, which are held in the @attributes hash, as were they first-class methods. So a Person class with a name attribute can use Person#name and Person#name= and never directly use the attributes hash – except for multiple assigns with ActiveRecord#attributes=. A Milestone class can also ask Milestone#completed? to test that the completed attribute is not nil or 0.
It’s also possible to instantiate related objects, so a Client class belonging to the clients table with a master_id foreign key can instantiate master through Client#master.
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 |
# File 'lib/active_record/base.rb', line 1171 def method_missing(method_id, *arguments) method_name = method_id.id2name if method_name =~ read_method? && @attributes.include?($1) return read_attribute($1) elsif method_name =~ read_untyped_method? && @attributes.include?($1) return read_attribute_before_type_cast($1) elsif method_name =~ write_method? && @attributes.include?($1) write_attribute($1, arguments[0]) elsif method_name =~ query_method? && @attributes.include?($1) return query_attribute($1) else super end end |
Class Method Details
.===(object) ⇒ Object
Overwrite the default class equality method to provide support for association proxies.
700 701 702 |
# File 'lib/active_record/base.rb', line 700 def ===(object) object.is_a?(self) end |
.accessible_attributes ⇒ Object
Returns an array of all the attributes that have been made accessible to mass-assignment.
509 510 511 |
# File 'lib/active_record/base.rb', line 509 def accessible_attributes # :nodoc: read_inheritable_attribute("attr_accessible") end |
.attr_accessible(*attributes) ⇒ Object
If this macro is used, only those attributed named in it will be accessible for mass-assignment, such as new(attributes)
and attributes=(attributes)
. This is the more conservative choice for mass-assignment protection. If you’d rather start from an all-open default and restrict attributes as needed, have a look at attr_protected.
504 505 506 |
# File 'lib/active_record/base.rb', line 504 def attr_accessible(*attributes) write_inheritable_array("attr_accessible", attributes) end |
.attr_protected(*attributes) ⇒ Object
Attributes named in this macro are protected from mass-assignment, such as new(attributes)
and attributes=(attributes)
. Their assignment will simply be ignored. Instead, you can use the direct writer methods to do assignment. This is meant to protect sensitive attributes to be overwritten by URL/form hackers. Example:
class Customer < ActiveRecord::Base
attr_protected :credit_rating
end
customer = Customer.new("name" => David, "credit_rating" => "Excellent")
customer. # => nil
customer.attributes = { "description" => "Jolly fellow", "credit_rating" => "Superb" }
customer. # => nil
customer. = "Average"
customer. # => "Average"
491 492 493 |
# File 'lib/active_record/base.rb', line 491 def attr_protected(*attributes) write_inheritable_array("attr_protected", attributes) end |
.benchmark(title) ⇒ Object
Used to aggregate logging and benchmark, so you can measure and represent multiple statements in a single block. Usage (hides all the SQL calls for the individual actions and calculates total runtime for them all):
Project.benchmark("Creating project") do
project = Project.create("name" => "stuff")
project.create_manager("name" => "David")
project.milestones << Milestone.find_all
end
682 683 684 685 686 687 |
# File 'lib/active_record/base.rb', line 682 def benchmark(title) result = nil bm = Benchmark.measure { result = silence { yield } } logger.info "#{title} (#{sprintf("%f", bm.real)})" if logger return result end |
.class_name(table_name = table_name) ⇒ Object
Turns the table_name
back into a class name following the reverse rules of table_name
.
605 606 607 608 609 610 |
# File 'lib/active_record/base.rb', line 605 def class_name(table_name = table_name) # :nodoc: # remove any prefix and/or suffix from the table name class_name = Inflector.camelize(table_name[table_name_prefix.length..-(table_name_suffix.length + 1)]) class_name = Inflector.singularize(class_name) if pluralize_table_names return class_name end |
.column_methods_hash ⇒ Object
Returns a hash of all the methods added to query each of the columns in the table with the name of the method as the key and true as the value. This makes it possible to do O(1) lookups in respond_to? to check if a given method for attribute is available.
635 636 637 638 639 640 641 642 643 |
# File 'lib/active_record/base.rb', line 635 def column_methods_hash @dynamic_methods_hash ||= columns_hash.keys.inject(Hash.new(false)) do |methods, attr| methods[attr.to_sym] = true methods["#{attr}=".to_sym] = true methods["#{attr}?".to_sym] = true methods["#{attr}_before_type_cast".to_sym] = true methods end end |
.column_names ⇒ Object
622 623 624 |
# File 'lib/active_record/base.rb', line 622 def column_names @column_names ||= columns_hash.keys end |
.columns ⇒ Object
Returns an array of column objects for the table associated with this class.
613 614 615 |
# File 'lib/active_record/base.rb', line 613 def columns @columns ||= connection.columns(table_name, "#{name} Columns") end |
.columns_hash ⇒ Object
Returns an array of column objects for the table associated with this class.
618 619 620 |
# File 'lib/active_record/base.rb', line 618 def columns_hash @columns_hash ||= columns.inject({}) { |hash, column| hash[column.name] = column; hash } end |
.connected? ⇒ Boolean
Returns true if a connection that’s accessible to this class have already been opened.
109 110 111 112 113 114 115 116 117 118 119 |
# File 'lib/active_record/connection_adapters/abstract_adapter.rb', line 109 def self.connected? klass = self until klass == ActiveRecord::Base.superclass if Thread.current['active_connections'].is_a?(Hash) && Thread.current['active_connections'][klass] return true else klass = klass.superclass end end return false end |
.connection ⇒ Object
Returns the connection currently associated with the class. This can also be used to “borrow” the connection to do database work unrelated to any of the specific Active Records.
234 235 236 |
# File 'lib/active_record/base.rb', line 234 def self.connection retrieve_connection end |
.connection=(spec) ⇒ Object
Set the connection for the class.
134 135 136 137 138 139 |
# File 'lib/active_record/connection_adapters/abstract_adapter.rb', line 134 def self.connection=(spec) raise ConnectionNotEstablished unless spec conn = self.send(spec.adapter_method, spec.config) Thread.current['active_connections'] ||= {} Thread.current['active_connections'][self] = conn end |
.content_columns ⇒ Object
Returns an array of columns objects where the primary id, all columns ending in “_id” or “_count”, and columns used for single table inheritance has been removed.
628 629 630 |
# File 'lib/active_record/base.rb', line 628 def content_columns @content_columns ||= columns.reject { |c| c.name == primary_key || c.name =~ /(_id|_count)$/ || c.name == inheritance_column } end |
.count(conditions = nil, joins = nil) ⇒ Object
Returns the number of records that meets the conditions
. Zero is returned if no records match. Example:
Product.count "sales > 1"
440 441 442 443 444 445 446 |
# File 'lib/active_record/base.rb', line 440 def count(conditions = nil, joins = nil) tbl_var_name = joins ? table_name[0,1].downcase : "" sql = "SELECT COUNT(*) FROM #{table_name} #{tbl_var_name} " sql << ", #{joins} " if joins add_conditions!(sql, conditions) count_by_sql(sql) end |
.count_by_sql(sql) ⇒ Object
Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part.
Product.count "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id"
450 451 452 453 454 455 456 457 458 459 460 |
# File 'lib/active_record/base.rb', line 450 def count_by_sql(sql) sql = sanitize_conditions(sql) rows = connection.select_one(sql, "#{name} Count") if rows.nil? return 0 else count = rows.values.first return count ? count.to_i : 0 end end |
.create(attributes = nil) ⇒ Object
Creates an object, instantly saves it as a record (if the validation permits it), and returns it. If the save fail under validations, the unsaved object is still returned.
378 379 380 381 382 383 384 385 386 |
# File 'lib/active_record/base.rb', line 378 def create(attributes = nil) if attributes.is_a?(Array) attributes.collect { |attr| create(attr) } else object = new(attributes) object.save object end end |
.decrement_counter(counter_name, id) ⇒ Object
Works like increment_counter, but decrements instead.
472 473 474 |
# File 'lib/active_record/base.rb', line 472 def decrement_counter(counter_name, id) update_all "#{counter_name} = #{counter_name} - 1", "#{primary_key} = #{quote(id)}" end |
.delete(id) ⇒ Object
Deletes the record with the given id
without instantiating an object first. If an array of ids is provided, all of them are deleted.
403 404 405 |
# File 'lib/active_record/base.rb', line 403 def delete(id) delete_all([ "#{primary_key} IN (?)", id ]) end |
.delete_all(conditions = nil) ⇒ Object
Deletes all the records that matches the condition
without instantiating the objects first (and hence not calling the destroy method). Example:
Post.destroy_all "person_id = 5 AND (category = 'Something' OR category = 'Else')"
432 433 434 435 436 |
# File 'lib/active_record/base.rb', line 432 def delete_all(conditions = nil) sql = "DELETE FROM #{table_name} " add_conditions!(sql, conditions) connection.delete(sql, "#{name} Delete all") end |
.descends_from_active_record? ⇒ Boolean
:nodoc:
661 662 663 |
# File 'lib/active_record/base.rb', line 661 def descends_from_active_record? # :nodoc: superclass == Base || !columns_hash.has_key?(inheritance_column) end |
.destroy(id) ⇒ Object
Destroys the record with the given id
by instantiating the object and calling #destroy (all the callbacks are the triggered). If an array of ids is provided, all of them are destroyed.
409 410 411 |
# File 'lib/active_record/base.rb', line 409 def destroy(id) id.is_a?(Array) ? id.each { |id| destroy(id) } : find(id).destroy end |
.destroy_all(conditions = nil) ⇒ Object
Destroys the objects for all the records that matches the condition
by instantiating each object and calling the destroy method. Example:
Person.destroy_all "last_login < '2004-04-04'"
425 426 427 |
# File 'lib/active_record/base.rb', line 425 def destroy_all(conditions = nil) find_all(conditions).each { |object| object.destroy } end |
.establish_connection(spec = nil) ⇒ Object
Establishes the connection to the database. Accepts a hash as input where the :adapter key must be specified with the name of a database adapter (in lower-case) example for regular databases (MySQL, Postgresql, etc):
ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:host => "localhost",
:username => "myuser",
:password => "mypass",
:database => "somedatabase"
)
Example for SQLite database:
ActiveRecord::Base.establish_connection(
:adapter => "sqlite",
:dbfile => "path/to/dbfile"
)
Also accepts keys as strings (for parsing from yaml for example):
ActiveRecord::Base.establish_connection(
"adapter" => "sqlite",
"dbfile" => "path/to/dbfile"
)
The exceptions AdapterNotSpecified, AdapterNotFound and ArgumentError may be returned on an error.
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
# File 'lib/active_record/connection_adapters/abstract_adapter.rb', line 66 def self.establish_connection(spec = nil) case spec when nil raise AdapterNotSpecified unless defined? RAILS_ENV establish_connection(RAILS_ENV) when ConnectionSpecification @@defined_connections[self] = spec when Symbol, String if configuration = configurations[spec.to_s] establish_connection(configuration) else raise AdapterNotSpecified, "#{spec} database is not configured" end else spec = spec.symbolize_keys unless spec.key?(:adapter) then raise AdapterNotSpecified, "database configuration does not specify adapter" end adapter_method = "#{spec[:adapter]}_connection" unless respond_to?(adapter_method) then raise AdapterNotFound, "database configuration specifies nonexistent #{spec[:adapter]} adapter" end remove_connection establish_connection(ConnectionSpecification.new(spec, adapter_method)) end end |
.exists?(id) ⇒ Boolean
Returns true if the given id
represents the primary key of a record in the database, false otherwise. Example:
Person.exists?(5)
372 373 374 |
# File 'lib/active_record/base.rb', line 372 def exists?(id) !find(:first, :conditions => ["#{primary_key} = ?", id]).nil? rescue false end |
.find(*args) ⇒ Object
Find operates with three different retreval approaches:
-
Find by id: This can either be a specific id (1), a list of ids (1, 5, 6), or an array of ids ([5, 6, 10]). If no record can be found for all of the listed ids, then RecordNotFound will be raised.
-
Find first: This will return the first record matched by the options used. These options can either be specific conditions or merely an order. If no record can matched, nil is returned.
-
Find all: This will return all the records matched by the options used. If no records are found, an empty array is returned.
All approaches accepts an option hash as their last parameter. The options are:
-
:conditions
: An SQL fragment like “administrator = 1” or [ “user_name = ?”, username ]. See conditions in the intro. -
:order
: An SQL fragment like “created_at DESC, name”. -
:limit
: An integer determining the limit on the number of rows that should be returned. -
:offset
: An integer determining the offset from where the rows should be fetched. So at 5, it would skip the first 4 rows. -
:joins
: An SQL fragment for additional joins like “LEFT JOIN comments ON comments.post_id = id”. (Rarely needed). -
:include
: Names associations that should be loaded alongside using LEFT OUTER JOINs. The symbols named refer to already defined associations. See eager loading under Associations.
Examples for find by id:
Person.find(1) # returns the object for ID = 1
Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
Person.find([7, 17]) # returns an array for objects with IDs in (7, 17)
Person.find([1]) # returns an array for objects the object with ID = 1
Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC")
Examples for find first:
Person.find(:first) # returns the first object fetched by SELECT * FROM people
Person.find(:first, :conditions => [ "user_name = ?", user_name])
Person.find(:first, :order => "created_on DESC", :offset => 5)
Examples for find all:
Person.find(:all) # returns an array of objects for all the rows fetched by SELECT * FROM people
Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50)
Person.find(:all, :offset => 10, :limit => 10)
Person.find(:all, :include => [ :account, :friends ])
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 |
# File 'lib/active_record/base.rb', line 327 def find(*args) = (args) case args.first when :first find(:all, .merge({ :limit => 1 })).first when :all [:include] ? find_with_associations() : find_by_sql(construct_finder_sql()) else expects_array = args.first.kind_of?(Array) conditions = " AND #{sanitize_sql([:conditions])}" if [:conditions] ids = args.flatten.compact.uniq case ids.size when 0 raise RecordNotFound, "Couldn't find #{name} without an ID#{conditions}" when 1 if result = find(:first, .merge({ :conditions => "#{table_name}.#{primary_key} = #{sanitize(ids.first)}#{conditions}" })) return expects_array ? [ result ] : result else raise RecordNotFound, "Couldn't find #{name} with ID=#{ids.first}#{conditions}" end else # Find multiple ids ids_list = ids.map { |id| sanitize(id) }.join(',') result = find(:all, .merge({ :conditions => "#{table_name}.#{primary_key} IN (#{ids_list})#{conditions}", :order => primary_key })) if result.size == ids.size return result else raise RecordNotFound, "Couldn't find all #{name.pluralize} with IDs (#{ids_list})#{conditions}" end end end end |
.find_all(conditions = nil, orderings = nil, limit = nil, joins = nil) ⇒ Object
This method is deprecated in favor of find(:all, options).
Returns an array of all the objects that could be instantiated from the associated table in the database. The conditions
can be used to narrow the selection of objects (WHERE-part), such as by “color = ‘red’”, and arrangement of the selection can be done through orderings
(ORDER BY-part), such as by “last_name, first_name DESC”. A maximum of returned objects and their offset can be specified in limit
with either just a single integer as the limit or as an array with the first element as the limit, the second as the offset. Examples:
Project.find_all "category = 'accounts'", "last_accessed DESC", 15
Project.find_all ["category = ?", category_name], "created ASC", [15, 20]
35 36 37 38 |
# File 'lib/active_record/deprecated_finders.rb', line 35 def find_all(conditions = nil, orderings = nil, limit = nil, joins = nil) # :nodoc: limit, offset = limit.is_a?(Array) ? limit : [ limit, nil ] find(:all, :conditions => conditions, :order => orderings, :joins => joins, :limit => limit, :offset => offset) end |
.find_by_sql(sql) ⇒ Object
Works like find_all, but requires a complete SQL string. Examples:
Post.find_by_sql "SELECT p.*, c.author FROM posts p, comments c WHERE p.id = c.post_id"
Post.find_by_sql ["SELECT * FROM posts WHERE author = ? AND created > ?", , start_date]
365 366 367 |
# File 'lib/active_record/base.rb', line 365 def find_by_sql(sql) connection.select_all(sanitize_sql(sql), "#{name} Load").inject([]) { |objects, record| objects << instantiate(record) } end |
.find_first(conditions = nil, orderings = nil, joins = nil) ⇒ Object
This method is deprecated in favor of find(:first, options).
Returns the object for the first record responding to the conditions in conditions
, such as “group = ‘master’”. If more than one record is returned from the query, it’s the first that’ll be used to create the object. In such cases, it might be beneficial to also specify orderings
, like “income DESC, name”, to control exactly which record is to be used. Example:
Employee.find_first "income > 50000", "income DESC, name"
21 22 23 |
# File 'lib/active_record/deprecated_finders.rb', line 21 def find_first(conditions = nil, orderings = nil, joins = nil) # :nodoc: find(:first, :conditions => conditions, :order => orderings, :joins => joins) end |
.find_on_conditions(ids, conditions) ⇒ Object
This method is deprecated in favor of find with the :conditions option.
Works like find, but the record matching id
must also meet the conditions
. RecordNotFound
is raised if no record can be found matching the id
or meeting the condition. Example:
Person.find_on_conditions 5, "first_name LIKE '%dav%' AND last_name = 'heinemeier'"
10 11 12 |
# File 'lib/active_record/deprecated_finders.rb', line 10 def find_on_conditions(ids, conditions) # :nodoc: find(ids, :conditions => conditions) end |
.human_attribute_name(attribute_key_name) ⇒ Object
Transforms attribute key names into a more humane format, such as “First name” instead of “first_name”. Example:
Person.human_attribute_name("first_name") # => "First name"
Deprecated in favor of just calling “first_name”.humanize
657 658 659 |
# File 'lib/active_record/base.rb', line 657 def human_attribute_name(attribute_key_name) #:nodoc: attribute_key_name.humanize end |
.increment_counter(counter_name, id) ⇒ Object
Increments the specified counter by one. So DiscussionBoard.increment_counter("post_count", discussion_board_id)
would increment the “post_count” counter on the board responding to discussion_board_id. This is used for caching aggregate values, so that they doesn’t need to be computed every time. Especially important for looping over a collection where each element require a number of aggregate values. Like the DiscussionBoard that needs to list both the number of posts and comments.
467 468 469 |
# File 'lib/active_record/base.rb', line 467 def increment_counter(counter_name, id) update_all "#{counter_name} = #{counter_name} + 1", "#{primary_key} = #{quote(id)}" end |
.inheritance_column ⇒ Object
Defines the column name for use with single table inheritance – can be overridden in subclasses.
557 558 559 |
# File 'lib/active_record/base.rb', line 557 def inheritance_column "type" end |
.inherited(child) ⇒ Object
:nodoc:
245 246 247 248 249 |
# File 'lib/active_record/base.rb', line 245 def self.inherited(child) #:nodoc: @@subclasses[self] ||= [] @@subclasses[self] << child super end |
.mysql_connection(config) ⇒ Object
Establishes a connection to the database that’s used by all Active Record objects.
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/active_record/connection_adapters/mysql_adapter.rb', line 7 def self.mysql_connection(config) # :nodoc: unless self.class.const_defined?(:Mysql) begin # Only include the MySQL driver if one hasn't already been loaded require_library_or_gem 'mysql' rescue LoadError => cannot_require_mysql # Only use the supplied backup Ruby/MySQL driver if no driver is already in place begin require 'active_record/vendor/mysql' require 'active_record/vendor/mysql411' rescue LoadError raise cannot_require_mysql end end end symbolize_strings_in_hash(config) host = config[:host] port = config[:port] socket = config[:socket] username = config[:username] ? config[:username].to_s : 'root' password = config[:password].to_s if config.has_key?(:database) database = config[:database] else raise ArgumentError, "No database specified. Missing argument: database." end mysql = Mysql.init mysql.ssl_set(config[:sslkey], config[:sslcert], config[:sslca], config[:sslcapath], config[:sslcipher]) if config[:sslkey] ConnectionAdapters::MysqlAdapter.new(mysql.real_connect(host, username, password, database, port, socket), logger, [host, username, password, database, port, socket]) end |
.postgresql_connection(config) ⇒ Object
Establishes a connection to the database that’s used by all Active Record objects
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 19 def self.postgresql_connection(config) # :nodoc: require_library_or_gem 'postgres' unless self.class.const_defined?(:PGconn) symbolize_strings_in_hash(config) host = config[:host] port = config[:port] || 5432 unless host.nil? username = config[:username].to_s password = config[:password].to_s schema_order = config[:schema_order] if config.has_key?(:database) database = config[:database] else raise ArgumentError, "No database specified. Missing argument: database." end pga = ConnectionAdapters::PostgreSQLAdapter.new( PGconn.connect(host, port, "", "", database, username, password), logger ) pga.execute("SET search_path TO #{schema_order}") if schema_order pga end |
.primary_key ⇒ Object
Defines the primary key field – can be overridden in subclasses. Overwriting will negate any effect of the primary_key_prefix_type setting, though.
545 546 547 548 549 550 551 552 553 554 |
# File 'lib/active_record/base.rb', line 545 def primary_key case primary_key_prefix_type when :table_name Inflector.foreign_key(class_name_of_active_record_descendant(self), false) when :table_name_with_underscore Inflector.foreign_key(class_name_of_active_record_descendant(self)) else "id" end end |
.protected_attributes ⇒ Object
Returns an array of all the attributes that have been protected from mass-assignment.
496 497 498 |
# File 'lib/active_record/base.rb', line 496 def protected_attributes # :nodoc: read_inheritable_attribute("attr_protected") end |
.quote(object) ⇒ Object
:nodoc:
665 666 667 |
# File 'lib/active_record/base.rb', line 665 def quote(object) #:nodoc: connection.quote(object) end |
.remove_connection(klass = self) ⇒ Object
Remove the connection for this class. This will close the active connection and the defined connection (if they exist). The result can be used as argument for establish_connection, for easy re-establishing of the connection.
125 126 127 128 129 130 131 |
# File 'lib/active_record/connection_adapters/abstract_adapter.rb', line 125 def self.remove_connection(klass=self) conn = @@defined_connections[klass] @@defined_connections.delete(klass) Thread.current['active_connections'] ||= {} Thread.current['active_connections'][klass] = nil conn.config if conn end |
.reset_column_information ⇒ Object
Resets all the cached information about columns, which will cause they to be reloaded on the next request.
646 647 648 |
# File 'lib/active_record/base.rb', line 646 def reset_column_information @column_names = @columns = @columns_hash = @content_columns = @dynamic_methods_hash = nil end |
.reset_column_information_and_inheritable_attributes_for_all_subclasses ⇒ Object
:nodoc:
650 651 652 |
# File 'lib/active_record/base.rb', line 650 def reset_column_information_and_inheritable_attributes_for_all_subclasses#:nodoc: subclasses.each { |klass| klass.reset_inheritable_attributes; klass.reset_column_information } end |
.retrieve_connection ⇒ Object
Locate the connection of the nearest super class. This can be an active or defined connections: if it is the latter, it will be opened and set as the active connection for the class it was defined for (not necessarily the current class).
93 94 95 96 97 98 99 100 101 102 103 104 105 106 |
# File 'lib/active_record/connection_adapters/abstract_adapter.rb', line 93 def self.retrieve_connection #:nodoc: klass = self until klass == ActiveRecord::Base.superclass Thread.current['active_connections'] ||= {} if Thread.current['active_connections'][klass] return Thread.current['active_connections'][klass] elsif @@defined_connections[klass] klass.connection = @@defined_connections[klass] return self.connection end klass = klass.superclass end raise ConnectionNotEstablished end |
.sanitize(object) ⇒ Object
Used to sanitize objects before they’re used in an SELECT SQL-statement. Delegates to connection.quote
.
670 671 672 |
# File 'lib/active_record/base.rb', line 670 def sanitize(object) #:nodoc: connection.quote(object) end |
.serialize(attr_name, class_name = Object) ⇒ Object
Specifies that the attribute by the name of attr_name
should be serialized before saving to the database and unserialized after loading from the database. The serialization is done through YAML. If class_name
is specified, the serialized object must be of that class on retrieval or SerializationTypeMismatch
will be raised.
516 517 518 |
# File 'lib/active_record/base.rb', line 516 def serialize(attr_name, class_name = Object) write_inheritable_attribute("attr_serialized", serialized_attributes.update(attr_name.to_s => class_name)) end |
.serialized_attributes ⇒ Object
Returns a hash of all the attributes that have been specified for serialization as keys and their class restriction as values.
521 522 523 |
# File 'lib/active_record/base.rb', line 521 def serialized_attributes read_inheritable_attribute("attr_serialized") || { } end |
.set_inheritance_column(value = nil, &block) ⇒ Object Also known as: inheritance_column=
Sets the name of the inheritance column to use to the given value, or (if the value # is nil or false) to the value returned by the given block.
Example:
class Project < ActiveRecord::Base
set_inheritance_column do
original_inheritance_column + "_id"
end
end
599 600 601 |
# File 'lib/active_record/base.rb', line 599 def set_inheritance_column( value=nil, &block ) define_attr_method :inheritance_column, value, &block end |
.set_primary_key(value = nil, &block) ⇒ Object Also known as: primary_key=
Sets the name of the primary key column to use to the given value, or (if the value is nil or false) to the value returned by the given block.
Example:
class Project < ActiveRecord::Base
set_primary_key "sysid"
end
583 584 585 |
# File 'lib/active_record/base.rb', line 583 def set_primary_key( value=nil, &block ) define_attr_method :primary_key, value, &block end |
.set_table_name(value = nil, &block) ⇒ Object Also known as: table_name=
Sets the table name to use to the given value, or (if the value is nil or false) to the value returned by the given block.
Example:
class Project < ActiveRecord::Base
set_table_name "project"
end
569 570 571 |
# File 'lib/active_record/base.rb', line 569 def set_table_name( value=nil, &block ) define_attr_method :table_name, value, &block end |
.silence ⇒ Object
Silences the logger for the duration of the block.
690 691 692 693 694 695 696 697 |
# File 'lib/active_record/base.rb', line 690 def silence result = nil old_logger_level = logger.level if logger logger.level = Logger::ERROR if logger result = yield logger.level = old_logger_level if logger return result end |
.sqlite3_connection(config) ⇒ Object
sqlite3 adapter reuses sqlite_connection.
11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 11 def sqlite3_connection(config) # :nodoc: parse_config!(config) unless self.class.const_defined?(:SQLite3) require_library_or_gem(config[:adapter]) end db = SQLite3::Database.new( config[:dbfile], :results_as_hash => true, :type_translation => false ) ConnectionAdapters::SQLiteAdapter.new(db, logger) end |
.sqlite_connection(config) ⇒ Object
Establishes a connection to the database that’s used by all Active Record objects
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 27 def sqlite_connection(config) # :nodoc: parse_config!(config) unless self.class.const_defined?(:SQLite) require_library_or_gem(config[:adapter]) db = SQLite::Database.new(config[:dbfile], 0) db.show_datatypes = "ON" if !defined? SQLite::Version db.results_as_hash = true if defined? SQLite::Version db.type_translation = false # "Downgrade" deprecated sqlite API if SQLite.const_defined?(:Version) ConnectionAdapters::SQLiteAdapter.new(db, logger) else ConnectionAdapters::DeprecatedSQLiteAdapter.new(db, logger) end end end |
.symbolize_strings_in_hash(hash) ⇒ Object
Converts all strings in a hash to symbols.
142 143 144 |
# File 'lib/active_record/connection_adapters/abstract_adapter.rb', line 142 def self.symbolize_strings_in_hash(hash) #:nodoc: hash.symbolize_keys end |
.table_name ⇒ Object
Guesses the table name (in forced lower-case) based on the name of the class in the inheritance hierarchy descending directly from ActiveRecord. So if the hierarchy looks like: Reply < Message < ActiveRecord, then Message is used to guess the table name from even when called on Reply. The rules used to do the guess are handled by the Inflector class in Active Support, which knows almost all common English inflections (report a bug if your inflection isn’t covered).
Additionally, the class-level table_name_prefix is prepended to the table_name and the table_name_suffix is appended. So if you have “myapp_” as a prefix, the table name guess for an Account class becomes “myapp_accounts”.
You can also overwrite this class method to allow for unguessable links, such as a Mouse class with a link to a “mice” table. Example:
class Mouse < ActiveRecord::Base
set_table_name "mice"
end
539 540 541 |
# File 'lib/active_record/base.rb', line 539 def table_name table_name_prefix + undecorated_table_name(class_name_of_active_record_descendant(self)) + table_name_suffix end |
.timestamps_gmt ⇒ Object
:nodoc:
55 56 57 58 |
# File 'lib/active_record/timestamp.rb', line 55 def self. #:nodoc: warn "timestamps_gmt is deprecated. use default_timezone instead" self.default_timezone == :utc end |
.timestamps_gmt=(gmt) ⇒ Object
:nodoc:
50 51 52 53 |
# File 'lib/active_record/timestamp.rb', line 50 def self.( gmt ) #:nodoc: warn "timestamps_gmt= is deprecated. use default_timezone= instead" self.default_timezone = ( gmt ? :utc : :local ) end |
.update(id, attributes) ⇒ Object
Finds the record from the passed id
, instantly saves it with the passed attributes
(if the validation permits it), and returns it. If the save fail under validations, the unsaved object is still returned.
390 391 392 393 394 395 396 397 398 399 |
# File 'lib/active_record/base.rb', line 390 def update(id, attributes) if id.is_a?(Array) idx = -1 id.collect { |id| idx += 1; update(id, attributes[idx]) } else object = find(id) object.update_attributes(attributes) object end end |
.update_all(updates, conditions = nil) ⇒ Object
Updates all records with the SET-part of an SQL update statement in updates
and returns an integer with the number of rows updates. A subset of the records can be selected by specifying conditions
. Example:
Billing.update_all "category = 'authorized', approved = 1", "author = 'David'"
416 417 418 419 420 |
# File 'lib/active_record/base.rb', line 416 def update_all(updates, conditions = nil) sql = "UPDATE #{table_name} SET #{sanitize_sql(updates)} " add_conditions!(sql, conditions) return connection.update(sql, "#{name} Update") end |
Instance Method Details
#==(comparison_object) ⇒ Object
Returns true if the comparison_object
is the same object, or is of the same type and has the same id.
1100 1101 1102 |
# File 'lib/active_record/base.rb', line 1100 def ==(comparison_object) comparison_object.equal?(self) or (comparison_object.instance_of?(self.class) and comparison_object.id == id) end |
#[](attr_name) ⇒ Object
Returns the value of attribute identified by attr_name
after it has been type cast (for example, “2004-12-12” in a data column is cast to a date object, like Date.new(2004, 12, 12)). (Alias for the protected read_attribute method).
1044 1045 1046 |
# File 'lib/active_record/base.rb', line 1044 def [](attr_name) read_attribute(attr_name.to_s) end |
#[]=(attr_name, value) ⇒ Object
Updates the attribute identified by attr_name
with the specified value
. (Alias for the protected write_attribute method).
1050 1051 1052 |
# File 'lib/active_record/base.rb', line 1050 def []= (attr_name, value) write_attribute(attr_name.to_s, value) end |
#attribute_names ⇒ Object
Returns an array of names for the attributes available on this object sorted alphabetically.
1090 1091 1092 |
# File 'lib/active_record/base.rb', line 1090 def attribute_names @attributes.keys.sort end |
#attribute_present?(attribute) ⇒ Boolean
Returns true if the specified attribute
has been set by the user or by a database load and is neither nil nor empty? (the latter only applies to objects that responds to empty?, most notably Strings).
1084 1085 1086 1087 |
# File 'lib/active_record/base.rb', line 1084 def attribute_present?(attribute) is_empty = read_attribute(attribute).respond_to?("empty?") ? read_attribute(attribute).empty? : false @attributes.include?(attribute) && !@attributes[attribute].nil? && !is_empty end |
#attributes ⇒ Object
Returns a hash of all the attributes with their names as keys and clones of their objects as values.
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 |
# File 'lib/active_record/base.rb', line 1071 def attributes self.attribute_names.inject({}) do |attributes, name| begin attributes[name] = read_attribute(name).clone rescue TypeError, NoMethodError attributes[name] = read_attribute(name) end attributes end end |
#attributes=(attributes) ⇒ Object
Allows you to set all the attributes at once by passing in a hash with keys matching the attribute names (which again matches the column names). Sensitive attributes can be protected from this form of mass-assignment by using the attr_protected
macro. Or you can alternatively specify which attributes can be accessed in with the attr_accessible
macro. Then all the attributes not included in that won’t be allowed to be mass-assigned.
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 |
# File 'lib/active_record/base.rb', line 1059 def attributes=(attributes) return if attributes.nil? attributes.stringify_keys! multi_parameter_attributes = [] remove_attributes_protected_from_mass_assignment(attributes).each do |k, v| k.include?("(") ? multi_parameter_attributes << [ k, v ] : send(k + "=", v) end assign_multiparameter_attributes(multi_parameter_attributes) end |
#clone ⇒ Object
Returns a clone of the record that hasn’t been assigned an id yet and is treated as a new record.
977 978 979 980 981 982 |
# File 'lib/active_record/base.rb', line 977 def clone attrs = self.attributes attrs.delete(self.class.primary_key) cloned_record = self.class.new(attrs) cloned_record end |
#column_for_attribute(name) ⇒ Object
Returns the column object for the named attribute.
1095 1096 1097 |
# File 'lib/active_record/base.rb', line 1095 def column_for_attribute(name) self.class.columns_hash[name.to_s] end |
#connection ⇒ Object
Returns the connection currently associated with the class. This can also be used to “borrow” the connection to do database work that isn’t easily done without going straight to SQL.
241 242 243 |
# File 'lib/active_record/base.rb', line 241 def connection self.class.connection end |
#decrement(attribute) ⇒ Object
Initializes the attribute
to zero if nil and subtracts one. Only makes sense for number-based attributes. Returns self.
1012 1013 1014 1015 1016 |
# File 'lib/active_record/base.rb', line 1012 def decrement(attribute) self[attribute] ||= 0 self[attribute] -= 1 self end |
#decrement!(attribute) ⇒ Object
Decrements the attribute
and saves the record.
1019 1020 1021 |
# File 'lib/active_record/base.rb', line 1019 def decrement!(attribute) decrement(attribute).update_attribute(attribute, self[attribute]) end |
#destroy ⇒ Object
Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can’t be persisted).
964 965 966 967 968 969 970 971 972 973 974 |
# File 'lib/active_record/base.rb', line 964 def destroy unless new_record? connection.delete( "DELETE FROM #{self.class.table_name} " + "WHERE #{self.class.primary_key} = #{quote(id)}", "#{self.class.name} Destroy" ) end freeze end |
#eql?(comparison_object) ⇒ Boolean
Delegates to ==
1105 1106 1107 |
# File 'lib/active_record/base.rb', line 1105 def eql?(comparison_object) self == (comparison_object) end |
#hash ⇒ Object
Delegates to id in order to allow two records of the same type and id to work with something like:
[ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]
1111 1112 1113 |
# File 'lib/active_record/base.rb', line 1111 def hash id.hash end |
#id ⇒ Object Also known as: to_param
Every Active Record class must use “id” as their primary ID. This getter overwrites the native id method, which isn’t being used in this context.
931 932 933 |
# File 'lib/active_record/base.rb', line 931 def id read_attribute(self.class.primary_key) end |
#id=(value) ⇒ Object
Sets the primary ID.
947 948 949 |
# File 'lib/active_record/base.rb', line 947 def id=(value) write_attribute(self.class.primary_key, value) end |
#id_before_type_cast ⇒ Object
:nodoc:
938 939 940 |
# File 'lib/active_record/base.rb', line 938 def id_before_type_cast #:nodoc: read_attribute_before_type_cast(self.class.primary_key) end |
#increment(attribute) ⇒ Object
Initializes the attribute
to zero if nil and adds one. Only makes sense for number-based attributes. Returns self.
1000 1001 1002 1003 1004 |
# File 'lib/active_record/base.rb', line 1000 def increment(attribute) self[attribute] ||= 0 self[attribute] += 1 self end |
#increment!(attribute) ⇒ Object
Increments the attribute
and saves the record.
1007 1008 1009 |
# File 'lib/active_record/base.rb', line 1007 def increment!(attribute) increment(attribute).update_attribute(attribute, self[attribute]) end |
#locking_enabled? ⇒ Boolean
:nodoc:
53 54 55 |
# File 'lib/active_record/locking.rb', line 53 def locking_enabled? #:nodoc: lock_optimistically && respond_to?(:lock_version) end |
#new_record? ⇒ Boolean
Returns true if this object hasn’t been saved yet – that is, a record for the object doesn’t exist yet.
952 953 954 |
# File 'lib/active_record/base.rb', line 952 def new_record? @new_record end |
#quoted_id ⇒ Object
:nodoc:
942 943 944 |
# File 'lib/active_record/base.rb', line 942 def quoted_id #:nodoc: quote(id, self.class.columns_hash[self.class.primary_key]) end |
#reload ⇒ Object
Reloads the attributes of this object from the database.
1035 1036 1037 1038 1039 |
# File 'lib/active_record/base.rb', line 1035 def reload clear_association_cache @attributes.update(self.class.find(self.id).instance_variable_get('@attributes')) return self end |
#respond_to?(method, include_priv = false) ⇒ Boolean
A Person object with a name attribute can ask person.respond_to?(“name”), person.respond_to?(“name=”), and person.respond_to?(“name?”) which will all return true.
1120 1121 1122 |
# File 'lib/active_record/base.rb', line 1120 def respond_to?(method, include_priv = false) self.class.column_methods_hash[method.to_sym] || respond_to_without_attributes?(method, include_priv) end |
#respond_to_without_attributes? ⇒ Object
For checking respond_to? without searching the attributes (which is faster).
1116 |
# File 'lib/active_record/base.rb', line 1116 alias_method :respond_to_without_attributes?, :respond_to? |
#save ⇒ Object
-
No record exists: Creates a new record with values matching those of the object attributes.
-
A record does exist: Updates the record with values matching those of the object attributes.
958 959 960 |
# File 'lib/active_record/base.rb', line 958 def save create_or_update end |
#toggle(attribute) ⇒ Object
Turns an attribute
that’s currently true into false and vice versa. Returns self.
1024 1025 1026 1027 |
# File 'lib/active_record/base.rb', line 1024 def toggle(attribute) self[attribute] = quote(!send("#{attribute}?", column_for_attribute(attribute))) self end |
#toggle!(attribute) ⇒ Object
Toggles the attribute
and saves the record.
1030 1031 1032 |
# File 'lib/active_record/base.rb', line 1030 def toggle!(attribute) toggle(attribute).update_attribute(attribute, self[attribute]) end |
#update_attribute(name, value) ⇒ Object
Updates a single attribute and saves the record. This is especially useful for boolean flags on existing records. Note: This method is overwritten by the Validation module that’ll make sure that updates made with this method doesn’t get subjected to validation checks. Hence, attributes can be updated even if the full object isn’t valid.
987 988 989 990 |
# File 'lib/active_record/base.rb', line 987 def update_attribute(name, value) self[name] = value save end |
#update_attributes(attributes) ⇒ Object
Updates all the attributes in from the passed hash and saves the record. If the object is invalid, the saving will fail and false will be returned.
994 995 996 997 |
# File 'lib/active_record/base.rb', line 994 def update_attributes(attributes) self.attributes = attributes return save end |