Class: ActiveRecord::Base

Inherits:
Object
  • Object
show all
Includes:
ClassInheritableAttributes
Defined in:
lib/active_record/base.rb,
lib/active_record/connection_adapters/abstract_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 = '%s' AND password = '%s'", 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

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.

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

The class -> [adapter_method, config] map

{}

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ClassInheritableAttributes

append_features

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:



606
607
608
609
610
611
612
# File 'lib/active_record/base.rb', line 606

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.



781
782
783
784
785
786
787
788
789
790
791
792
793
# File 'lib/active_record/base.rb', line 781

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 =~ write_method?
    write_attribute($1, arguments[0])
  elsif method_name =~ query_method?
    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.



398
399
400
# File 'lib/active_record/base.rb', line 398

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.



393
394
395
# File 'lib/active_record/base.rb', line 393

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"


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

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


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

def benchmark(title)
  logger.level = Logger::ERROR
  bm = Benchmark.measure { yield }
  logger.level = Logger::DEBUG
  logger.info "#{title} (#{sprintf("%f", bm.real)})"
end

.class_name(table_name = table_name) ⇒ Object

Turns the table_name back into a class name following the reverse rules of table_name.



468
469
470
471
472
473
# File 'lib/active_record/base.rb', line 468

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

.columnsObject

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



476
477
478
# File 'lib/active_record/base.rb', line 476

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.



481
482
483
# File 'lib/active_record/base.rb', line 481

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)


90
91
92
93
94
95
96
97
98
99
100
# File 'lib/active_record/connection_adapters/abstract_adapter.rb', line 90

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.



171
172
173
# File 'lib/active_record/base.rb', line 171

def self.connection
  retrieve_connection
end

.connection=(spec) ⇒ Object

Set the connection for the class.



115
116
117
118
119
120
# File 'lib/active_record/connection_adapters/abstract_adapter.rb', line 115

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.



487
488
489
# File 'lib/active_record/base.rb', line 487

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


338
339
340
341
342
# File 'lib/active_record/base.rb', line 338

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"


346
347
348
349
# File 'lib/active_record/base.rb', line 346

def count_by_sql(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.



296
297
298
299
300
# File 'lib/active_record/base.rb', line 296

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

.decrement_counter(counter_name, id) ⇒ Object

Works like increment_counter, but decrements instead.



361
362
363
# File 'lib/active_record/base.rb', line 361

def decrement_counter(counter_name, id)
  update_all "#{counter_name} = #{counter_name} - 1", "#{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')"


330
331
332
333
334
# File 'lib/active_record/base.rb', line 330

def delete_all(conditions = nil)
  sql = "DELETE FROM #{table_name} "
  add_conditions!(sql, conditions)
  connection.delete(sql, "#{name} Delete all")
end

.descents_from_active_record?Boolean

:nodoc:

Returns:

  • (Boolean)


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

def descents_from_active_record? # :nodoc:
  superclass == Base
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'"


323
324
325
# File 'lib/active_record/base.rb', line 323

def destroy_all(conditions = nil)
  find_all(conditions).each { |object| object.destroy }
end

.establish_connection(spec) ⇒ 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( ... )


55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/active_record/connection_adapters/abstract_adapter.rb', line 55

def self.establish_connection(spec)
  if spec.instance_of? ConnectionSpecification
    @@defined_connections[self] = spec
  else
    if spec.nil? then raise AdapterNotSpecified end
    symbolize_strings_in_hash(spec)
    unless spec.key?(:adapter) then raise AdapterNotSpecified end

    adapter_method = "#{spec[:adapter]}_connection"
    unless methods.include?(adapter_method) then raise AdapterNotFound end
    remove_connection
    @@defined_connections[self] = ConnectionSpecification.new(spec, adapter_method)
  end
end

.find(*ids) ⇒ 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)

RecordNotFound is raised if no record can be found.



222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/active_record/base.rb', line 222

def find(*ids)
  ids = [ ids ].flatten.compact

  if ids.length > 1
    ids_list = ids.map{ |id| "'#{sanitize(id)}'" }.join(", ")
    objects  = find_all("#{primary_key} IN (#{ids_list})", primary_key)

    if objects.length == ids.length
      return objects
    else
      raise RecordNotFound, "Couldn't find #{name} with ID in (#{ids_list})"
    end
  elsif ids.length == 1
    id = ids.first
    sql = "SELECT * FROM #{table_name} WHERE #{primary_key} = '#{sanitize(id)}'"
    sql << " AND #{type_condition}" unless descents_from_active_record?

    if record = connection.select_one(sql, "#{name} Find")
      instantiate(record)
    else 
      raise RecordNotFound, "Couldn't find #{name} with ID = #{id}"
    end
  else
    raise RecordNotFound, "Couldn't find #{name} without an ID"
  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 can be specified in limit. Example:

Project.find_all "category = 'accounts'", "last_accessed DESC", 15


263
264
265
266
267
268
269
270
271
# File 'lib/active_record/base.rb', line 263

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?
  sql << "LIMIT #{limit} " unless limit.nil?
    
  find_by_sql(sql)
end

.find_by_sql(sql) ⇒ Object

Works like find_all, but requires a complete SQL string. Example:

Post.find_by_sql "SELECT p.*, c.author FROM posts p, comments c WHERE p.id = c.post_id"


275
276
277
# File 'lib/active_record/base.rb', line 275

def find_by_sql(sql)
  connection.select_all(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"


284
285
286
287
288
289
290
291
292
# File 'lib/active_record/base.rb', line 284

def find_first(conditions = nil, orderings = nil)
  sql  = "SELECT * FROM #{table_name} "
  add_conditions!(sql, conditions)
  sql << "ORDER BY #{orderings} " unless orderings.nil?
  sql << "LIMIT 1"
    
  record = connection.select_one(sql, "#{name} Load First")
  instantiate(record) unless record.nil?
end

.find_on_conditions(id, conditions) ⇒ Object

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


253
254
255
256
# File 'lib/active_record/base.rb', line 253

def find_on_conditions(id, conditions)
  find_first("#{primary_key} = '#{sanitize(id)}' AND #{sanitize_conditions(conditions)}") || 
      raise(RecordNotFound, "Couldn't find #{name} with #{primary_key} = #{id} on the condition of #{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"


493
494
495
# File 'lib/active_record/base.rb', line 493

def human_attribute_name(attribute_key_name)
  attribute_key_name.gsub(/_/, " ").capitalize unless attribute_key_name.nil?
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.



356
357
358
# File 'lib/active_record/base.rb', line 356

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

.inheritance_columnObject

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



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

def inheritance_column
 "type"
end

.inherited(child) ⇒ Object

:nodoc:



182
183
184
185
186
# File 'lib/active_record/base.rb', line 182

def self.inherited(child) #:nodoc:
  @@subclasses[self] ||= []
  @@subclasses[self] << child
  super
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.



451
452
453
454
455
456
457
458
459
460
# File 'lib/active_record/base.rb', line 451

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.



385
386
387
# File 'lib/active_record/base.rb', line 385

def protected_attributes # :nodoc:
  read_inheritable_attribute("attr_protected")
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.



106
107
108
109
110
111
112
# File 'lib/active_record/connection_adapters/abstract_adapter.rb', line 106

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

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



74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/active_record/connection_adapters/abstract_adapter.rb', line 74

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.



502
503
504
505
# File 'lib/active_record/base.rb', line 502

def sanitize(object) # :nodoc:
  return object if Fixnum === object
  object.to_s.gsub(/([;:])/, "").gsub('##', '\#\#').gsub(/'/, "''") # ' (for ruby-mode)
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.



405
406
407
# File 'lib/active_record/base.rb', line 405

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.



410
411
412
# File 'lib/active_record/base.rb', line 410

def serialized_attributes
  read_inheritable_attribute("attr_serialized") || { }
end

.symbolize_strings_in_hash(hash) ⇒ Object

Converts all strings in a hash to symbols.



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

def self.symbolize_strings_in_hash(hash)
  hash.each do |key, value|
    if key.class == String
      hash.delete key
      hash[key.intern] = value
    end
  end
end

.table_name(class_name = nil) ⇒ 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 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


440
441
442
443
444
445
446
447
# File 'lib/active_record/base.rb', line 440

def table_name(class_name = nil)
  if class_name.nil?
    class_name  = class_name_of_active_record_descendant(self)
    table_name_prefix + undecorated_table_name(class_name) + table_name_suffix
  else
    table_name_prefix + undecorated_table_name(class_name) + table_name_suffix
  end
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.



304
305
306
307
308
309
# File 'lib/active_record/base.rb', line 304

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. A subset of the records can be selected by specifying conditions. Example:

Billing.update_all "category = 'authorized', approved = 1", "author = 'David'"


314
315
316
317
318
# File 'lib/active_record/base.rb', line 314

def update_all(updates, conditions = nil)
  sql  = "UPDATE #{table_name} SET #{updates} "
  add_conditions!(sql, conditions)
  connection.update(sql, "#{name} Update")
end

Instance Method Details

#==(comparison_object) ⇒ Object

Returns true if the comparison_object is of the same type and has the same id.



721
722
723
# File 'lib/active_record/base.rb', line 721

def ==(comparison_object)
  comparison_object.instance_of?(self.class) && 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).



678
679
680
# File 'lib/active_record/base.rb', line 678

def [](attr_name) 
  read_attribute(attr_name)
end

#[]=(attr_name, value) ⇒ Object

Updates the attribute identified by attr_name with the specified value. (Alias for the protected write_attribute method).



684
685
686
# File 'lib/active_record/base.rb', line 684

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

#attribute_namesObject

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



711
712
713
# File 'lib/active_record/base.rb', line 711

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)


705
706
707
708
# File 'lib/active_record/base.rb', line 705

def attribute_present?(attribute)
  is_empty = read_attribute(attribute).respond_to?("empty?") ? read_attribute(attribute).empty? : false
  @attributes.include?(attribute) && !@attributes[attribute].nil? && !is_empty
end

#attributes=(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.



693
694
695
696
697
698
699
700
701
# File 'lib/active_record/base.rb', line 693

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.



652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
# File 'lib/active_record/base.rb', line 652

def clone
  attr = Hash.new

  self.attribute_names.each do |name|
    begin
      attr[name] = read_attribute(name).clone
    rescue TypeError
      attr[name] = read_attribute(name)
    end
  end

  cloned_record = self.class.new(attr)
  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.



716
717
718
# File 'lib/active_record/base.rb', line 716

def column_for_attribute(name)
  self.class.columns_hash[name]
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.



178
179
180
# File 'lib/active_record/base.rb', line 178

def connection
  self.class.connection
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).



639
640
641
642
643
644
645
646
647
648
649
# File 'lib/active_record/base.rb', line 639

def destroy
  unless new_record?
    connection.delete(
      "DELETE FROM #{self.class.table_name} " + 
      "WHERE #{self.class.primary_key} = '#{id}'", 
      "#{self.class.name} Destroy"
    )
  end

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



616
617
618
# File 'lib/active_record/base.rb', line 616

def id
  read_attribute(self.class.primary_key)
end

#id=(value) ⇒ Object

Sets the primary ID.



621
622
623
# File 'lib/active_record/base.rb', line 621

def id=(value)
  write_attribute(self.class.primary_key, value)
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)


626
627
628
# File 'lib/active_record/base.rb', line 626

def new_record?
  @new_record
end

#respond_to?(method) ⇒ 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)


730
731
732
733
# File 'lib/active_record/base.rb', line 730

def respond_to?(method)
  @@dynamic_methods ||= attribute_names + attribute_names.collect { |attr| attr + "=" } + attribute_names.collect { |attr| attr + "?" }
  @@dynamic_methods.include?(method.to_s) ? true : respond_to_without_attributes?(method)
end

#respond_to_without_attributes?Object

For checking respond_to? without searching the attributes (which is faster).



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

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.



632
633
634
635
# File 'lib/active_record/base.rb', line 632

def save
  create_or_update
  return true
end

#update_attribute(name, value) ⇒ Object

Updates a single attribute and saves the record. This is especially useful for boolean flags on existing records.



670
671
672
673
# File 'lib/active_record/base.rb', line 670

def update_attribute(name, value)
  self[name] = value
  save
end