Class: ActiveRecord::Base

Inherits:
Object show all
Includes:
ClassInheritableAttributes
Defined in:
lib/active_record/base.rb,
lib/active_record/locking.rb,
lib/active_record/timestamp.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("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).

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

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_first and find_all. For example, the full interface for Payment.find_all_by_amount is actually Payment.find_all_by_amount(amount, orderings = nil, limit = nil, joins = nil). And the full interface to Person.find_by_user_name is actually Person.find_by_user_name(user_name, orderings = nil)

Saving arrays, hashes, and other non-mappeable 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 optional :class_name option 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, :class_name => "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 with 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 in establish_connection didn’t include a :adapter key.

  • AdapterNotSpecified – the :adapter key used in establish_connection specified an unexisting 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 in the :class_name option of the serialize definition.

  • ConnectionNotEstablished – no connection has been established. Use establish_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.

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
@@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
@@defined_connections =

The class -> [adapter_method, config] map

{}

Class Method Summary collapse

Instance Method Summary collapse

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.

Yields:

  • (_self)

Yield Parameters:



756
757
758
759
760
761
762
# File 'lib/active_record/base.rb', line 756

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.



1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
# File 'lib/active_record/base.rb', line 1002

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

.accessible_attributesObject

Returns an array of all the attributes that have been made accessible to mass-assigment.



455
456
457
# File 'lib/active_record/base.rb', line 455

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.



450
451
452
# File 'lib/active_record/base.rb', line 450

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.credit_rating # => nil
customer.attributes = { "description" => "Jolly fellow", "credit_rating" => "Superb" }
customer.credit_rating # => nil

customer.credit_rating = "Average"
customer.credit_rating # => "Average"


437
438
439
# File 'lib/active_record/base.rb', line 437

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


592
593
594
595
596
597
598
599
# File 'lib/active_record/base.rb', line 592

def benchmark(title)
  result = nil
  logger.level = Logger::ERROR
  bm = Benchmark.measure { result = yield }
  logger.level = Logger::DEBUG
  logger.info "#{title} (#{sprintf("%f", bm.real)})"
  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.



520
521
522
523
524
525
# File 'lib/active_record/base.rb', line 520

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_hashObject

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.



546
547
548
549
550
551
552
553
554
# File 'lib/active_record/base.rb', line 546

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

.columnsObject

Returns an array of column objects for the table associated with this class.



528
529
530
# File 'lib/active_record/base.rb', line 528

def columns
  @columns ||= connection.columns(table_name, "#{name} Columns")
end

.columns_hashObject

Returns an array of column objects for the table associated with this class.



533
534
535
# File 'lib/active_record/base.rb', line 533

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.

Returns:

  • (Boolean)


121
122
123
124
125
126
127
128
129
130
131
# File 'lib/active_record/connection_adapters/abstract_adapter.rb', line 121

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

.connectionObject

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.



195
196
197
# File 'lib/active_record/base.rb', line 195

def self.connection
  retrieve_connection
end

.connection=(spec) ⇒ Object

Set the connection for the class.



146
147
148
149
150
151
# File 'lib/active_record/connection_adapters/abstract_adapter.rb', line 146

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_columnsObject

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.



539
540
541
# File 'lib/active_record/base.rb', line 539

def content_columns
  @content_columns ||= columns.reject { |c| c.name == primary_key || c.name =~ /(_id|_count)$/ || c.name == inheritance_column }
end

.count(conditions = nil) ⇒ Object

Returns the number of records that meets the conditions. Zero is returned if no records match. Example:

Product.count "sales > 1"


394
395
396
397
398
# File 'lib/active_record/base.rb', line 394

def count(conditions = nil)
  sql  = "SELECT COUNT(*) FROM #{table_name} "
  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"


402
403
404
405
406
# File 'lib/active_record/base.rb', line 402

def count_by_sql(sql)
  sql = sanitize_conditions(sql)
  count = connection.select_one(sql, "#{name} Count").values.first
  return count ? count.to_i : 0
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.



342
343
344
345
346
# File 'lib/active_record/base.rb', line 342

def create(attributes = nil)
  object = new(attributes)
  object.save
  object
end

.decrement_counter(counter_name, id) ⇒ Object

Works like increment_counter, but decrements instead.



418
419
420
# File 'lib/active_record/base.rb', line 418

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.



358
359
360
# File 'lib/active_record/base.rb', line 358

def delete(id)
  delete_all([ "#{primary_key} = ?", 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')"


386
387
388
389
390
# File 'lib/active_record/base.rb', line 386

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:

Returns:

  • (Boolean)


571
572
573
# File 'lib/active_record/base.rb', line 571

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).



363
364
365
# File 'lib/active_record/base.rb', line 363

def 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'"


379
380
381
# File 'lib/active_record/base.rb', line 379

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.

Connecting to another database for a single model

To support different connections for different classes, you can simply call establish_connection with the classes you wish to have different connections for:

class Courses < ActiveRecord::Base
 ...
end

Courses.establish_connection( ... )


78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/active_record/connection_adapters/abstract_adapter.rb', line 78

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

.find(*args) ⇒ Object

Returns objects for the records responding to either a specific id (1), a list of ids (1, 5, 6) or an array of ids. If only one ID is specified, that object is returned directly. If more than one ID is specified, an array is returned. Examples:

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

The last argument may be a Hash of find options. Currently, conditions is the only option, behaving the same as with find_all.

Person.find(1, :conditions => "associate_id = 5"
Person.find(1, 2, 6, :conditions => "status = 'active'"
Person.find([7, 17], :conditions => ["sanitize_me = ?", "bare'quote"]

RecordNotFound is raised if no record can be found.



261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'lib/active_record/base.rb', line 261

def find(*args)
  # Return an Array if ids are passed in an Array.
  expects_array = args.first.kind_of?(Array)

  # Extract options hash from argument list.
  options = extract_options_from_args!(args)
  conditions = " AND #{sanitize_sql(options[:conditions])}" if options[:conditions]

  ids = args.flatten.compact.uniq
  case ids.size

    # Raise if no ids passed.
    when 0
      raise RecordNotFound, "Couldn't find #{name} without an ID#{conditions}"

    # Find a single id.
    when 1
      unless result = find_first("#{primary_key} = #{sanitize(ids.first)}#{conditions}")
        raise RecordNotFound, "Couldn't find #{name} with ID=#{ids.first}#{conditions}"
      end

      # Box result if expecting array.
      expects_array ? [result] : result

    # Find multiple ids.
    else
      ids_list = ids.map { |id| sanitize(id) }.join(',')
      result   = find_all("#{primary_key} IN (#{ids_list})#{conditions}", primary_key)
      if result.size == ids.size
        result
      else
        raise RecordNotFound, "Couldn't find #{name} with ID in (#{ids_list})#{conditions}"
      end
  end
end

.find_all(conditions = nil, orderings = nil, limit = nil, joins = nil) ⇒ Object

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 (LIMIT…OFFSET-part). Examples:

Project.find_all "category = 'accounts'", "last_accessed DESC", 15
Project.find_all ["category = ?", category_name], "created ASC", ["? OFFSET ?", 15, 20]


313
314
315
316
317
318
319
320
321
322
# File 'lib/active_record/base.rb', line 313

def find_all(conditions = nil, orderings = nil, limit = nil, joins = nil)
  sql  = "SELECT * FROM #{table_name} " 
  sql << "#{joins} " if joins
  add_conditions!(sql, conditions)
  sql << "ORDER BY #{orderings} " unless orderings.nil?

  connection.add_limit!(sql, sanitize_sql(limit)) unless limit.nil?

  find_by_sql(sql)
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 > ?", author_id, start_date]


327
328
329
# File 'lib/active_record/base.rb', line 327

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) ⇒ Object

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"


336
337
338
# File 'lib/active_record/base.rb', line 336

def find_first(conditions = nil, orderings = nil)
  find_all(conditions, orderings, 1).first
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'"


302
303
304
# File 'lib/active_record/base.rb', line 302

def find_on_conditions(ids, conditions)
  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"


567
568
569
# File 'lib/active_record/base.rb', line 567

def human_attribute_name(attribute_key_name)
  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.



413
414
415
# File 'lib/active_record/base.rb', line 413

def increment_counter(counter_name, id)
  update_all "#{counter_name} = #{counter_name} + 1", "#{primary_key} = #{quote(id)}"
end

.inheritance_columnObject

Defines the column name for use with single table inheritance – can be overridden in subclasses.



515
516
517
# File 'lib/active_record/base.rb', line 515

def inheritance_column
  "type"
end

.inherited(child) ⇒ Object

:nodoc:



206
207
208
209
210
# File 'lib/active_record/base.rb', line 206

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
# 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

  ConnectionAdapters::MysqlAdapter.new(
    Mysql::real_connect(host, username, password, database, port, socket), logger
  )
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
# 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

  if config.has_key?(:database)
    database = config[:database]
  else
    raise ArgumentError, "No database specified. Missing argument: database."
  end

  ConnectionAdapters::PostgreSQLAdapter.new(
    PGconn.connect(host, port, "", "", database, username, password), logger
  )
end

.primary_keyObject

Defines the primary key field – can be overridden in subclasses. Overwritting will negate any effect of the primary_key_prefix_type setting, though.



503
504
505
506
507
508
509
510
511
512
# File 'lib/active_record/base.rb', line 503

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_attributesObject

Returns an array of all the attributes that have been protected from mass-assigment.



442
443
444
# File 'lib/active_record/base.rb', line 442

def protected_attributes # :nodoc:
  read_inheritable_attribute("attr_protected")
end

.quote(object) ⇒ Object



575
576
577
# File 'lib/active_record/base.rb', line 575

def quote(object)
  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.



137
138
139
140
141
142
143
# File 'lib/active_record/connection_adapters/abstract_adapter.rb', line 137

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_informationObject

Resets all the cached information about columns, which will cause they to be reloaded on the next request.



557
558
559
# File 'lib/active_record/base.rb', line 557

def reset_column_information
  @columns = @columns_hash = @content_columns = @dynamic_methods_hash = nil
end

.reset_column_information_and_inheritable_attributes_for_all_subclassesObject



561
562
563
# File 'lib/active_record/base.rb', line 561

def reset_column_information_and_inheritable_attributes_for_all_subclasses
  subclasses.each { |klass| klass.reset_inheritable_attributes; klass.reset_column_information }
end

.retrieve_connectionObject

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).



105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/active_record/connection_adapters/abstract_adapter.rb', line 105

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.



580
581
582
# File 'lib/active_record/base.rb', line 580

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 retrival or SerializationTypeMismatch will be raised.



462
463
464
# File 'lib/active_record/base.rb', line 462

def serialize(attr_name, class_name = Object)
  write_inheritable_attribute("attr_serialized", serialized_attributes.update(attr_name.to_s => class_name))
end

.serialized_attributesObject

Returns a hash of all the attributes that have been specified for serialization as keys and their class restriction as values.



467
468
469
# File 'lib/active_record/base.rb', line 467

def serialized_attributes
  read_inheritable_attribute("attr_serialized") || { }
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



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/active_record/connection_adapters/sqlserver_adapter.rb', line 31

def self.sqlserver_connection(config)
  require_library_or_gem 'dbi' unless self.class.const_defined?(:DBI)
  
  symbolize_strings_in_hash(config)

  host     = config[:host]
  username = config[:username] ? config[:username].to_s : 'sa'
  password = config[:password].to_s

  if config.has_key? :database
    database = config[:database]
  else
    raise ArgumentError, "No database specified. Missing argument: database."
  end

  conn = DBI.connect("DBI:ADO:Provider=SQLOLEDB;Data Source=#{host};Initial Catalog=#{database};User Id=#{username};Password=#{password};")
  conn["AutoCommit"] = true

  ConnectionAdapters::SQLServerAdapter.new(conn, logger)
end

.symbolize_strings_in_hash(hash) ⇒ Object

Converts all strings in a hash to symbols.



154
155
156
# File 'lib/active_record/connection_adapters/abstract_adapter.rb', line 154

def self.symbolize_strings_in_hash(hash)
  hash.symbolize_keys
end

.table_nameObject

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 guessing rules are as follows:

  • Class name ends in “x”, “ch” or “ss”: “es” is appended, so a Search class becomes a searches table.

  • Class name ends in “y” preceded by a consonant or “qu”: The “y” is replaced with “ies”, so a Category class becomes a categories table.

  • Class name ends in “fe”: The “fe” is replaced with “ves”, so a Wife class becomes a wives table.

  • Class name ends in “lf” or “rf”: The “f” is replaced with “ves”, so a Half class becomes a halves table.

  • Class name ends in “person”: The “person” is replaced with “people”, so a Salesperson class becomes a salespeople table.

  • Class name ends in “man”: The “man” is replaced with “men”, so a Spokesman class becomes a spokesmen table.

  • Class name ends in “sis”: The “i” is replaced with an “e”, so a Basis class becomes a bases table.

  • Class name ends in “tum” or “ium”: The “um” is replaced with an “a”, so a Datum class becomes a data table.

  • Class name ends in “child”: The “child” is replaced with “children”, so a NodeChild class becomes a node_children table.

  • Class name ends in an “s”: No additional characters are added or removed.

  • Class name doesn’t end in “s”: An “s” is appended, so a Comment class becomes a comments table.

  • Class name with word compositions: Compositions are underscored, so CreditCard class becomes a credit_cards table.

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
   def self.table_name() "mice" end
end


497
498
499
# File 'lib/active_record/base.rb', line 497

def table_name
  table_name_prefix + undecorated_table_name(class_name_of_active_record_descendant(self)) + table_name_suffix
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.



350
351
352
353
354
355
# File 'lib/active_record/base.rb', line 350

def update(id, attributes)
  object = find(id)
  object.attributes = attributes
  object.save
  object
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'"


370
371
372
373
374
# File 'lib/active_record/base.rb', line 370

def update_all(updates, conditions = nil)
  sql  = "UPDATE #{table_name} SET #{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.



931
932
933
# File 'lib/active_record/base.rb', line 931

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).



876
877
878
# File 'lib/active_record/base.rb', line 876

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).



882
883
884
# File 'lib/active_record/base.rb', line 882

def []= (attr_name, value) 
  write_attribute(attr_name.to_s, value)
end

#attribute_namesObject

Returns an array of names for the attributes available on this object sorted alphabetically.



921
922
923
# File 'lib/active_record/base.rb', line 921

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).

Returns:

  • (Boolean)


915
916
917
918
# File 'lib/active_record/base.rb', line 915

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

#attributesObject

Returns a hash of all the attributes with their names as keys and clones of their objects as values.



902
903
904
905
906
907
908
909
910
911
# File 'lib/active_record/base.rb', line 902

def attributes
  self.attribute_names.inject({}) do |attributes, name|
    begin
      attributes[name] = read_attribute(name).clone
    rescue TypeError
      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.



891
892
893
894
895
896
897
898
899
# File 'lib/active_record/base.rb', line 891

def attributes=(attributes)
  return if attributes.nil?

  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

#cloneObject

Returns a clone of the record that hasn’t been assigned an id yet and is treated as a new record.



809
810
811
812
813
814
# File 'lib/active_record/base.rb', line 809

def clone
  cloned_record = self.class.new(self.attributes)
  cloned_record.instance_variable_set "@new_record", true
  cloned_record.id = nil
  cloned_record
end

#column_for_attribute(name) ⇒ Object

Returns the column object for the named attribute.



926
927
928
# File 'lib/active_record/base.rb', line 926

def column_for_attribute(name)
  self.class.columns_hash[name.to_s]
end

#connectionObject

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.



202
203
204
# File 'lib/active_record/base.rb', line 202

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.



844
845
846
847
848
# File 'lib/active_record/base.rb', line 844

def decrement(attribute)
  self[attribute] ||= 0
  self[attribute] -= 1
  self
end

#decrement!(attribute) ⇒ Object

Decrements the attribute and saves the record.



851
852
853
# File 'lib/active_record/base.rb', line 851

def decrement!(attribute)
  decrement(attribute).update_attribute(attribute, self[attribute])
end

#destroyObject

Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can’t be persisted).



796
797
798
799
800
801
802
803
804
805
806
# File 'lib/active_record/base.rb', line 796

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 ==

Returns:

  • (Boolean)


936
937
938
# File 'lib/active_record/base.rb', line 936

def eql?(comparison_object)
  self == (comparison_object)
end

#hashObject

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) ]


942
943
944
# File 'lib/active_record/base.rb', line 942

def hash
  id
end

#idObject

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.



766
767
768
# File 'lib/active_record/base.rb', line 766

def id
  read_attribute(self.class.primary_key)
end

#id=(value) ⇒ Object

Sets the primary ID.



779
780
781
# File 'lib/active_record/base.rb', line 779

def id=(value)
  write_attribute(self.class.primary_key, value)
end

#id_before_type_castObject



770
771
772
# File 'lib/active_record/base.rb', line 770

def id_before_type_cast
  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.



832
833
834
835
836
# File 'lib/active_record/base.rb', line 832

def increment(attribute)
  self[attribute] ||= 0
  self[attribute] += 1
  self
end

#increment!(attribute) ⇒ Object

Increments the attribute and saves the record.



839
840
841
# File 'lib/active_record/base.rb', line 839

def increment!(attribute)
  increment(attribute).update_attribute(attribute, self[attribute])
end

#locking_enabled?Boolean

Returns:

  • (Boolean)


53
54
55
# File 'lib/active_record/locking.rb', line 53

def locking_enabled?
  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.

Returns:

  • (Boolean)


784
785
786
# File 'lib/active_record/base.rb', line 784

def new_record?
  @new_record
end

#quoted_idObject



774
775
776
# File 'lib/active_record/base.rb', line 774

def quoted_id
  quote(id, self.class.columns_hash[self.class.primary_key])
end

#reloadObject

Reloads the attributes of this object from the database.



867
868
869
870
871
# File 'lib/active_record/base.rb', line 867

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.

Returns:

  • (Boolean)


951
952
953
# File 'lib/active_record/base.rb', line 951

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).



947
# File 'lib/active_record/base.rb', line 947

alias_method :respond_to_without_attributes?, :respond_to?

#saveObject

  • 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.



790
791
792
# File 'lib/active_record/base.rb', line 790

def save
  create_or_update
end

#toggle(attribute) ⇒ Object

Turns an attribute that’s currently true into false and vice versa. Returns self.



856
857
858
859
# File 'lib/active_record/base.rb', line 856

def toggle(attribute)
  self[attribute] = quote(!send("#{attribute}?", column_for_attribute(attribute)))
  self
end

#toggle!(attribute) ⇒ Object

Toggles the attribute and saves the record.



862
863
864
# File 'lib/active_record/base.rb', line 862

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.



819
820
821
822
# File 'lib/active_record/base.rb', line 819

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.



826
827
828
829
# File 'lib/active_record/base.rb', line 826

def update_attributes(attributes)
  self.attributes = attributes
  return save
end