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/query_cache.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/sqlserver_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, :conditions => "user_name = '#{user_name}' AND password = '#{password}'")
end
def self.authenticate_safely(user_name, password)
find(:first, :conditions => [ "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_
or find_all_by_
, so you get finders like Person.find_by_user_name, Person.find_all_by_last_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)
. And instead of writing Person.find(:all, ["last_name = ?", last_name])
, you just do Person.find_all_by_last_name(last_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 =
{}
- @@configurations =
{}
- @@primary_key_prefix_type =
nil
- @@table_name_prefix =
""
- @@table_name_suffix =
""
- @@pluralize_table_names =
true
- @@colorize_logging =
true
- @@default_timezone =
:local
- @@threaded_connections =
true
- @@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.
-
.active_connections ⇒ Object
:nodoc:.
-
.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
Log and benchmark 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.
-
.sqlserver_connection(config) ⇒ Object
:nodoc:.
-
.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).
-
#attributes_before_type_cast ⇒ Object
Returns a hash of cloned attributes before typecasting and deserialization.
-
#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 ==.
-
#freeze ⇒ Object
Just freeze the attributes hash, such that associations are still accessible even on destroyed records.
- #frozen? ⇒ Boolean
-
#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.
927 928 929 930 931 932 933 |
# File 'lib/active_record/base.rb', line 927 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, *args, &block) ⇒ 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.
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 |
# File 'lib/active_record/base.rb', line 1184 def method_missing(method_id, *args, &block) method_name = method_id.to_s if @attributes.include?(method_name) read_attribute(method_name) elsif md = /(=|\?|_before_type_cast)$/.match(method_name) attribute_name, method_type = md.pre_match, md.to_s if @attributes.include?(attribute_name) case method_type when '=' write_attribute(attribute_name, args.first) when '?' query_attribute(attribute_name) when '_before_type_cast' read_attribute_before_type_cast(attribute_name) end else super end else super end end |
Class Method Details
.===(object) ⇒ Object
Overwrite the default class equality method to provide support for association proxies.
706 707 708 |
# File 'lib/active_record/base.rb', line 706 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.
517 518 519 |
# File 'lib/active_record/base.rb', line 517 def accessible_attributes # :nodoc: read_inheritable_attribute("attr_accessible") end |
.active_connections ⇒ Object
:nodoc:
89 90 91 92 93 94 95 |
# File 'lib/active_record/connection_adapters/abstract_adapter.rb', line 89 def self.active_connections #:nodoc: if threaded_connections Thread.current['active_connections'] ||= {} else @@active_connections ||= {} end 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.
512 513 514 |
# File 'lib/active_record/base.rb', line 512 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"
499 500 501 |
# File 'lib/active_record/base.rb', line 499 def attr_protected(*attributes) write_inheritable_array("attr_protected", attributes) end |
.benchmark(title) ⇒ Object
Log and benchmark 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
690 691 692 693 694 695 |
# File 'lib/active_record/base.rb', line 690 def benchmark(title) result = nil seconds = Benchmark.realtime { result = silence { yield } } logger.info "#{title} (#{sprintf("%f", seconds)})" 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
.
613 614 615 616 617 618 |
# File 'lib/active_record/base.rb', line 613 def class_name(table_name = table_name) # :nodoc: # remove any prefix and/or suffix from the table name class_name = table_name[table_name_prefix.length..-(table_name_suffix.length + 1)].camelize class_name = class_name.singularize if pluralize_table_names 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.
643 644 645 646 647 648 649 650 651 |
# File 'lib/active_record/base.rb', line 643 def column_methods_hash @dynamic_methods_hash ||= column_names.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
630 631 632 |
# File 'lib/active_record/base.rb', line 630 def column_names @column_names ||= columns.map { |column| column.name } end |
.columns ⇒ Object
Returns an array of column objects for the table associated with this class.
621 622 623 |
# File 'lib/active_record/base.rb', line 621 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.
626 627 628 |
# File 'lib/active_record/base.rb', line 626 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.
117 118 119 120 121 122 123 124 125 126 127 |
# File 'lib/active_record/connection_adapters/abstract_adapter.rb', line 117 def self.connected? klass = self until klass == ActiveRecord::Base.superclass if 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.
238 239 240 |
# File 'lib/active_record/base.rb', line 238 def self.connection retrieve_connection end |
.connection=(spec) ⇒ Object
Set the connection for the class.
47 48 49 50 51 52 53 54 55 |
# File 'lib/active_record/query_cache.rb', line 47 def self.connection=(spec) raise ConnectionNotEstablished unless spec conn = spec.config[:query_cache] ? QueryCache.new(self.send(spec.adapter_method, spec.config)) : self.send(spec.adapter_method, spec.config) 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.
636 637 638 |
# File 'lib/active_record/base.rb', line 636 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"
450 451 452 453 454 455 |
# File 'lib/active_record/base.rb', line 450 def count(conditions = nil, joins = nil) sql = "SELECT COUNT(*) FROM #{table_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"
459 460 461 462 463 464 465 466 467 468 |
# File 'lib/active_record/base.rb', line 459 def count_by_sql(sql) sql = sanitize_conditions(sql) rows = connection.select_one(sql, "#{name} Count") if !rows.nil? and count = rows.values.first count.to_i else 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.
388 389 390 391 392 393 394 395 396 |
# File 'lib/active_record/base.rb', line 388 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.
480 481 482 |
# File 'lib/active_record/base.rb', line 480 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.
413 414 415 |
# File 'lib/active_record/base.rb', line 413 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')"
442 443 444 445 446 |
# File 'lib/active_record/base.rb', line 442 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:
669 670 671 |
# File 'lib/active_record/base.rb', line 669 def descends_from_active_record? # :nodoc: superclass == Base || !columns_hash.include?(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.
419 420 421 |
# File 'lib/active_record/base.rb', line 419 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'"
435 436 437 |
# File 'lib/active_record/base.rb', line 435 def destroy_all(conditions = nil) find(:all, :conditions => 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)
382 383 384 |
# File 'lib/active_record/base.rb', line 382 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 ])
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 361 362 363 364 365 366 367 368 369 370 |
# File 'lib/active_record/base.rb', line 336 def find(*args) = (args) case args.first when :first find(:all, .merge([:include] ? { } : { :limit => 1 })).first when :all [:include] ? find_with_associations() : find_by_sql(construct_finder_sql()) else return args.first if args.first.kind_of?(Array) && args.first.empty? 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}"})) 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]
375 376 377 |
# File 'lib/active_record/base.rb', line 375 def find_by_sql(sql) connection.select_all(sanitize_sql(sql), "#{name} Load").collect! { |record| 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
665 666 667 |
# File 'lib/active_record/base.rb', line 665 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.
475 476 477 |
# File 'lib/active_record/base.rb', line 475 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.
565 566 567 |
# File 'lib/active_record/base.rb', line 565 def inheritance_column "type" end |
.inherited(child) ⇒ Object
:nodoc:
249 250 251 252 253 |
# File 'lib/active_record/base.rb', line 249 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 43 44 45 |
# 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 encoding = config[:encoding] = config[:min_messages] 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.schema_search_path = config[:schema_search_path] || config[:schema_order] pga.execute("SET client_encoding TO '#{encoding}'") if encoding pga.execute("SET client_min_messages TO '#{}'") if 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.
553 554 555 556 557 558 559 560 561 562 |
# File 'lib/active_record/base.rb', line 553 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.
504 505 506 |
# File 'lib/active_record/base.rb', line 504 def protected_attributes # :nodoc: read_inheritable_attribute("attr_protected") end |
.quote(object) ⇒ Object
:nodoc:
673 674 675 |
# File 'lib/active_record/base.rb', line 673 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.
133 134 135 136 137 138 |
# File 'lib/active_record/connection_adapters/abstract_adapter.rb', line 133 def self.remove_connection(klass=self) conn = @@defined_connections[klass] @@defined_connections.delete(klass) 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.
654 655 656 |
# File 'lib/active_record/base.rb', line 654 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:
658 659 660 |
# File 'lib/active_record/base.rb', line 658 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).
101 102 103 104 105 106 107 108 109 110 111 112 113 114 |
# File 'lib/active_record/connection_adapters/abstract_adapter.rb', line 101 def self.retrieve_connection #:nodoc: klass = self ar_super = ActiveRecord::Base.superclass until klass == ar_super if conn = active_connections[klass] return conn elsif conn = @@defined_connections[klass] klass.connection = conn 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
.
678 679 680 |
# File 'lib/active_record/base.rb', line 678 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.
524 525 526 |
# File 'lib/active_record/base.rb', line 524 def serialize(attr_name, class_name = Object) serialized_attributes[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.
529 530 531 |
# File 'lib/active_record/base.rb', line 529 def serialized_attributes read_inheritable_attribute("attr_serialized") or write_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
607 608 609 |
# File 'lib/active_record/base.rb', line 607 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
591 592 593 |
# File 'lib/active_record/base.rb', line 591 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
577 578 579 |
# File 'lib/active_record/base.rb', line 577 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.
698 699 700 701 702 703 |
# File 'lib/active_record/base.rb', line 698 def silence old_logger_level, logger.level = logger.level, Logger::ERROR if logger yield ensure logger.level = old_logger_level if logger 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 |
.sqlserver_connection(config) ⇒ Object
:nodoc:
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/active_record/connection_adapters/sqlserver_adapter.rb', line 16 def self.sqlserver_connection(config) #:nodoc: require_library_or_gem 'dbi' unless self.class.const_defined?(:DBI) symbolize_strings_in_hash(config) mode = config[:mode] ? config[:mode].to_s.upcase : 'ADO' username = config[:username] ? config[:username].to_s : 'sa' password = config[:password] ? config[:password].to_s : '' if mode == "ODBC" raise ArgumentError, "Missing DSN. Argument ':dsn' must be set in order for this adapter to work." unless config.has_key?(:dsn) dsn = config[:dsn] conn = DBI.connect("DBI:ODBC:#{dsn}", username, password) else raise ArgumentError, "Missing Database. Argument ':database' must be set in order for this adapter to work." unless config.has_key?(:database) database = config[:database] host = config[:host] ? config[:host].to_s : 'localhost' conn = DBI.connect("DBI:ADO:Provider=SQLOLEDB;Data Source=#{host};Initial Catalog=#{database};User Id=#{username};Password=#{password};") end conn["AutoCommit"] = true ConnectionAdapters::SQLServerAdapter.new(conn, logger) end |
.symbolize_strings_in_hash(hash) ⇒ Object
Converts all strings in a hash to symbols.
148 149 150 |
# File 'lib/active_record/connection_adapters/abstract_adapter.rb', line 148 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
547 548 549 |
# File 'lib/active_record/base.rb', line 547 def table_name "#{table_name_prefix}#{undecorated_table_name(class_name_of_active_record_descendant(self))}#{table_name_suffix}" end |
.timestamps_gmt ⇒ Object
:nodoc:
57 58 59 60 |
# File 'lib/active_record/timestamp.rb', line 57 def self. #:nodoc: warn "timestamps_gmt is deprecated. use default_timezone instead" self.default_timezone == :utc end |
.timestamps_gmt=(gmt) ⇒ Object
:nodoc:
52 53 54 55 |
# File 'lib/active_record/timestamp.rb', line 52 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.
400 401 402 403 404 405 406 407 408 409 |
# File 'lib/active_record/base.rb', line 400 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'"
426 427 428 429 430 |
# File 'lib/active_record/base.rb', line 426 def update_all(updates, conditions = nil) sql = "UPDATE #{table_name} SET #{sanitize_sql(updates)} " add_conditions!(sql, conditions) 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.
1104 1105 1106 |
# File 'lib/active_record/base.rb', line 1104 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).
1050 1051 1052 |
# File 'lib/active_record/base.rb', line 1050 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).
1056 1057 1058 |
# File 'lib/active_record/base.rb', line 1056 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.
1094 1095 1096 |
# File 'lib/active_record/base.rb', line 1094 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).
1088 1089 1090 1091 |
# File 'lib/active_record/base.rb', line 1088 def attribute_present?(attribute) value = read_attribute(attribute) !value.blank? or value == 0 end |
#attributes ⇒ Object
Returns a hash of all the attributes with their names as keys and clones of their objects as values.
1077 1078 1079 |
# File 'lib/active_record/base.rb', line 1077 def attributes clone_attributes :read_attribute 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.
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 |
# File 'lib/active_record/base.rb', line 1065 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 |
#attributes_before_type_cast ⇒ Object
Returns a hash of cloned attributes before typecasting and deserialization.
1082 1083 1084 |
# File 'lib/active_record/base.rb', line 1082 def attributes_before_type_cast clone_attributes :read_attribute_before_type_cast end |
#clone ⇒ Object
Returns a clone of the record that hasn’t been assigned an id yet and is treated as a new record.
982 983 984 985 986 987 988 |
# File 'lib/active_record/base.rb', line 982 def clone attrs = self.attributes_before_type_cast attrs.delete(self.class.primary_key) self.class.new do |record| record.send :instance_variable_set, '@attributes', attrs end end |
#column_for_attribute(name) ⇒ Object
Returns the column object for the named attribute.
1099 1100 1101 |
# File 'lib/active_record/base.rb', line 1099 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.
245 246 247 |
# File 'lib/active_record/base.rb', line 245 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.
1018 1019 1020 1021 1022 |
# File 'lib/active_record/base.rb', line 1018 def decrement(attribute) self[attribute] ||= 0 self[attribute] -= 1 self end |
#decrement!(attribute) ⇒ Object
Decrements the attribute
and saves the record.
1025 1026 1027 |
# File 'lib/active_record/base.rb', line 1025 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).
970 971 972 973 974 975 976 977 978 979 |
# File 'lib/active_record/base.rb', line 970 def destroy unless new_record? connection.delete <<-end_sql, "#{self.class.name} Destroy" DELETE FROM #{self.class.table_name} WHERE #{self.class.primary_key} = #{quoted_id} end_sql end freeze end |
#eql?(comparison_object) ⇒ Boolean
Delegates to ==
1109 1110 1111 |
# File 'lib/active_record/base.rb', line 1109 def eql?(comparison_object) self == (comparison_object) end |
#freeze ⇒ Object
Just freeze the attributes hash, such that associations are still accessible even on destroyed records.
1129 1130 1131 |
# File 'lib/active_record/base.rb', line 1129 def freeze @attributes.freeze end |
#frozen? ⇒ Boolean
1133 1134 1135 |
# File 'lib/active_record/base.rb', line 1133 def frozen? @attributes.frozen? 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) ]
1115 1116 1117 |
# File 'lib/active_record/base.rb', line 1115 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.
937 938 939 |
# File 'lib/active_record/base.rb', line 937 def id read_attribute(self.class.primary_key) end |
#id=(value) ⇒ Object
Sets the primary ID.
953 954 955 |
# File 'lib/active_record/base.rb', line 953 def id=(value) write_attribute(self.class.primary_key, value) end |
#id_before_type_cast ⇒ Object
:nodoc:
944 945 946 |
# File 'lib/active_record/base.rb', line 944 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.
1006 1007 1008 1009 1010 |
# File 'lib/active_record/base.rb', line 1006 def increment(attribute) self[attribute] ||= 0 self[attribute] += 1 self end |
#increment!(attribute) ⇒ Object
Increments the attribute
and saves the record.
1013 1014 1015 |
# File 'lib/active_record/base.rb', line 1013 def increment!(attribute) increment(attribute).update_attribute(attribute, self[attribute]) end |
#locking_enabled? ⇒ Boolean
:nodoc:
54 55 56 |
# File 'lib/active_record/locking.rb', line 54 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.
958 959 960 |
# File 'lib/active_record/base.rb', line 958 def new_record? @new_record end |
#quoted_id ⇒ Object
:nodoc:
948 949 950 |
# File 'lib/active_record/base.rb', line 948 def quoted_id #:nodoc: quote(id, column_for_attribute(self.class.primary_key)) end |
#reload ⇒ Object
Reloads the attributes of this object from the database.
1041 1042 1043 1044 1045 |
# File 'lib/active_record/base.rb', line 1041 def reload clear_association_cache @attributes.update(self.class.find(self.id).instance_variable_get('@attributes')) 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.
1124 1125 1126 |
# File 'lib/active_record/base.rb', line 1124 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).
1120 |
# File 'lib/active_record/base.rb', line 1120 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.
964 965 966 |
# File 'lib/active_record/base.rb', line 964 def save create_or_update end |
#toggle(attribute) ⇒ Object
Turns an attribute
that’s currently true into false and vice versa. Returns self.
1030 1031 1032 1033 |
# File 'lib/active_record/base.rb', line 1030 def toggle(attribute) self[attribute] = quote(!send("#{attribute}?", column_for_attribute(attribute))) self end |
#toggle!(attribute) ⇒ Object
Toggles the attribute
and saves the record.
1036 1037 1038 |
# File 'lib/active_record/base.rb', line 1036 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.
993 994 995 996 |
# File 'lib/active_record/base.rb', line 993 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.
1000 1001 1002 1003 |
# File 'lib/active_record/base.rb', line 1000 def update_attributes(attributes) self.attributes = attributes save end |