Class: ActiveRecord::Base

Inherits:
Object
  • 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

Accessing attributes before they have been type casted

Some times you want to be able to read the raw attribute data without having the column-determined type cast run its course first. That can be done by using the <attribute>_before_type_cast accessors that all attributes have. For example, if your Account model has a balance attribute, you can call account.balance_before_type_cast or account.id_before_type_cast.

This is especially useful in validation situations where the user might supply a string for an integer field and you want to display the original string back in an error message. Accessing the attribute normally would type cast the string to 0, which isn’t what you want.

Dynamic attribute-based finders

Dynamic attribute-based finders are a cleaner way of getting objects by simple queries without turning to SQL. They work by appending the name of an attribute to find_by_, so you get finders like Person.find_by_user_name, Payment.find_by_transaction_id. So instead of writing Person.find_first(["user_name = ?", user_name]), you just do Person.find_by_user_name(user_name).

It’s also possible to use multiple attributes in the same find by separating them with “and”, so you get finders like Person.find_by_user_name_and_password or even Payment.find_by_purchaser_and_state_and_country. So instead of writing Person.find_first(["user_name = ? AND password = ?", user_name, password]), you just do Person.find_by_user_name_and_password(user_name, password).

It’s even possible to use all the additional parameters to find_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-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 in establish_connection didn’t include a :adapter key.

  • AdapterNotSpecified – the :adapter key used in establish_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. 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.

  • MultiparameterAssignmentErrors – collection of errors that occurred during a mass assignment using the attributes= method. The errors property of this exception contains an array of AttributeAssignmentError objects that should be inspected to determine which attributes triggered the errors.

  • AttributeAssignmentError – an error occurred while doing a mass assignment through the attributes= method. You can inspect the attribute property of the exception object to determine which attribute triggered the error.

Note: The attributes listed are class-level attributes (accessible from both the class and instance level). So it’s possible to assign a logger to the class through Base.logger= which will then be used by all instances in the current object space.

Defined Under Namespace

Classes: ConnectionSpecification

Constant Summary collapse

@@subclasses =
{}
@@primary_key_prefix_type =
nil
@@table_name_prefix =
""
@@table_name_suffix =
""
@@pluralize_table_names =
true
@@colorize_logging =
true
@@default_timezone =
:local
@@lock_optimistically =
true
@@record_timestamps =

Records the creation date and possibly time in created_on (date only) or created_at (date and time) and the update date and possibly time in updated_on and updated_at. This only happens if the object responds to either of these messages, which they will do automatically if the table has columns of either of these names. This feature is turned on by default.

true
@@timestamps_gmt =

deprecated: use ActiveRecord::Base.default_timezone instead.

false
@@defined_connections =

The class -> [adapter_method, config] map

{}

Class Method Summary collapse

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:



878
879
880
881
882
883
884
# File 'lib/active_record/base.rb', line 878

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.



1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
# File 'lib/active_record/base.rb', line 1124

def method_missing(method_id, *arguments)
  method_name = method_id.id2name

  if method_name =~ read_method? && @attributes.include?($1)
    return read_attribute($1)
  elsif method_name =~ read_untyped_method? && @attributes.include?($1)
    return read_attribute_before_type_cast($1)
  elsif method_name =~ write_method? && @attributes.include?($1)
    write_attribute($1, arguments[0])
  elsif method_name =~ query_method? && @attributes.include?($1)
    return query_attribute($1)
  else
    super
  end
end

Class Method Details

.===(object) ⇒ Object

Overwrite the default class equality method to provide support for association proxies.



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

def ===(object)
  object.is_a?(self)
end

.accessible_attributesObject

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



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

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.



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

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"


479
480
481
# File 'lib/active_record/base.rb', line 479

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


666
667
668
669
670
671
# File 'lib/active_record/base.rb', line 666

def benchmark(title)
  result = nil
  bm = Benchmark.measure { result = silence { yield } }
  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.



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

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.



619
620
621
622
623
624
625
626
627
# File 'lib/active_record/base.rb', line 619

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.



601
602
603
# File 'lib/active_record/base.rb', line 601

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.



606
607
608
# File 'lib/active_record/base.rb', line 606

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)


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

def self.connected?
  klass = self
  until klass == ActiveRecord::Base.superclass
    if Thread.current['active_connections'].is_a?(Hash) && Thread.current['active_connections'][klass]
      return true 
    else
      klass = klass.superclass
    end
  end
  return false
end

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



221
222
223
# File 'lib/active_record/base.rb', line 221

def self.connection
  retrieve_connection
end

.connection=(spec) ⇒ Object

Set the connection for the class.



134
135
136
137
138
139
# File 'lib/active_record/connection_adapters/abstract_adapter.rb', line 134

def self.connection=(spec)
  raise ConnectionNotEstablished unless spec
  conn = self.send(spec.adapter_method, spec.config)
  Thread.current['active_connections'] ||= {}
  Thread.current['active_connections'][self] = conn
end

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



612
613
614
# File 'lib/active_record/base.rb', line 612

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"


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

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"


444
445
446
447
448
# File 'lib/active_record/base.rb', line 444

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.



374
375
376
377
378
379
380
381
382
# File 'lib/active_record/base.rb', line 374

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.



460
461
462
# File 'lib/active_record/base.rb', line 460

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.



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

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


428
429
430
431
432
# File 'lib/active_record/base.rb', line 428

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)


645
646
647
# File 'lib/active_record/base.rb', line 645

def descends_from_active_record? # :nodoc:
  superclass == Base || !columns_hash.has_key?(inheritance_column)
end

.destroy(id) ⇒ Object

Destroys the record with the given id by instantiating the object and calling #destroy (all the callbacks are the triggered). If an array of ids is provided, all of them are destroyed.



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

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


421
422
423
# File 'lib/active_record/base.rb', line 421

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

.establish_connection(spec = nil) ⇒ Object

Establishes the connection to the database. Accepts a hash as input where the :adapter key must be specified with the name of a database adapter (in lower-case) example for regular databases (MySQL, Postgresql, etc):

ActiveRecord::Base.establish_connection(
  :adapter  => "mysql",
  :host     => "localhost",
  :username => "myuser",
  :password => "mypass",
  :database => "somedatabase"
)

Example for SQLite database:

ActiveRecord::Base.establish_connection(
  :adapter => "sqlite",
  :dbfile  => "path/to/dbfile"
)

Also accepts keys as strings (for parsing from yaml for example):

ActiveRecord::Base.establish_connection(
  "adapter" => "sqlite",
  "dbfile"  => "path/to/dbfile"
)

The exceptions AdapterNotSpecified, AdapterNotFound and ArgumentError may be returned on an error.



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/active_record/connection_adapters/abstract_adapter.rb', line 66

def self.establish_connection(spec = nil)
  case spec
    when nil
      raise AdapterNotSpecified unless defined? RAILS_ENV
      establish_connection(RAILS_ENV)
    when ConnectionSpecification
      @@defined_connections[self] = spec
    when Symbol, String
      if configuration = configurations[spec.to_s]
        establish_connection(configuration)
      else
        raise AdapterNotSpecified, "#{spec} database is not configured"
      end
    else
      spec = spec.symbolize_keys
      unless spec.key?(:adapter) then raise AdapterNotSpecified, "database configuration does not specify adapter" end
      adapter_method = "#{spec[:adapter]}_connection"
      unless respond_to?(adapter_method) then raise AdapterNotFound, "database configuration specifies nonexistent #{spec[:adapter]} adapter" end
      remove_connection
      establish_connection(ConnectionSpecification.new(spec, adapter_method))
  end
end

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



293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/active_record/base.rb', line 293

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 all #{name.pluralize} with IDs (#{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]


345
346
347
348
349
350
351
352
353
354
# File 'lib/active_record/base.rb', line 345

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]


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

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"


368
369
370
# File 'lib/active_record/base.rb', line 368

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


334
335
336
# File 'lib/active_record/base.rb', line 334

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"

Deprecated in favor of just calling “first_name”.humanize



641
642
643
# File 'lib/active_record/base.rb', line 641

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.



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

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.



545
546
547
# File 'lib/active_record/base.rb', line 545

def inheritance_column
  "type"
end

.inherited(child) ⇒ Object

:nodoc:



232
233
234
235
236
# File 'lib/active_record/base.rb', line 232

def self.inherited(child) #:nodoc:
  @@subclasses[self] ||= []
  @@subclasses[self] << child
  super
end

.mysql_connection(config) ⇒ Object

Establishes a connection to the database that’s used by all Active Record objects.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/active_record/connection_adapters/mysql_adapter.rb', line 7

def self.mysql_connection(config) # :nodoc:
  unless self.class.const_defined?(:Mysql)
    begin
      # Only include the MySQL driver if one hasn't already been loaded
      require_library_or_gem 'mysql'
    rescue LoadError => cannot_require_mysql
      # Only use the supplied backup Ruby/MySQL driver if no driver is already in place
      begin 
        require 'active_record/vendor/mysql'
        require 'active_record/vendor/mysql411'
      rescue LoadError
        raise cannot_require_mysql
      end
    end
  end
 
  symbolize_strings_in_hash(config)
 
  host     = config[:host]
  port     = config[:port]
  socket   = config[:socket]
  username = config[:username] ? config[:username].to_s : 'root'
  password = config[:password].to_s
 
  if config.has_key?(:database)
    database = config[:database]
  else
    raise ArgumentError, "No database specified. Missing argument: database."
  end
 
  mysql = Mysql.init
  mysql.ssl_set(config[:sslkey], config[:sslcert], config[:sslca], config[:sslcapath], config[:sslcipher]) if config[:sslkey]
  ConnectionAdapters::MysqlAdapter.new(mysql.real_connect(host, username, password, database, port, socket), logger, [host, username, password, database, port, socket])
end

.postgresql_connection(config) ⇒ Object

Establishes a connection to the database that’s used by all Active Record objects



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 19

def self.postgresql_connection(config) # :nodoc:
  require_library_or_gem 'postgres' unless self.class.const_defined?(:PGconn)
  symbolize_strings_in_hash(config)
  host     = config[:host]
  port     = config[:port]     || 5432 unless host.nil?
  username = config[:username].to_s
  password = config[:password].to_s

  schema_order = config[:schema_order]

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

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

  pga.execute("SET search_path TO #{schema_order}") if schema_order

  pga
end

.primary_keyObject

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



533
534
535
536
537
538
539
540
541
542
# File 'lib/active_record/base.rb', line 533

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



484
485
486
# File 'lib/active_record/base.rb', line 484

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

.quote(object) ⇒ Object

:nodoc:



649
650
651
# File 'lib/active_record/base.rb', line 649

def quote(object) #:nodoc:
  connection.quote(object)
end

.remove_connection(klass = self) ⇒ Object

Remove the connection for this class. This will close the active connection and the defined connection (if they exist). The result can be used as argument for establish_connection, for easy re-establishing of the connection.



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

def self.remove_connection(klass=self)
  conn = @@defined_connections[klass]
  @@defined_connections.delete(klass)
  Thread.current['active_connections'] ||= {}
  Thread.current['active_connections'][klass] = nil
  conn.config if conn
end

.reset_column_informationObject

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



630
631
632
# File 'lib/active_record/base.rb', line 630

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

.reset_column_information_and_inheritable_attributes_for_all_subclassesObject

:nodoc:



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

def reset_column_information_and_inheritable_attributes_for_all_subclasses#:nodoc:
  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).



93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/active_record/connection_adapters/abstract_adapter.rb', line 93

def self.retrieve_connection #:nodoc:
  klass = self
  until klass == ActiveRecord::Base.superclass
    Thread.current['active_connections'] ||= {}
    if Thread.current['active_connections'][klass]
      return Thread.current['active_connections'][klass]
    elsif @@defined_connections[klass]
      klass.connection = @@defined_connections[klass]
      return self.connection
    end
    klass = klass.superclass
  end
  raise ConnectionNotEstablished
end

.sanitize(object) ⇒ Object

Used to sanitize objects before they’re used in an SELECT SQL-statement. Delegates to connection.quote.



654
655
656
# File 'lib/active_record/base.rb', line 654

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.



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

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.



509
510
511
# File 'lib/active_record/base.rb', line 509

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

.set_inheritance_column(value = nil, &block) ⇒ Object Also known as: inheritance_column=

Sets the name of the inheritance column to use to the given value, or (if the value # is nil or false) to the value returned by the given block.

Example:

class Project < ActiveRecord::Base
  set_inheritance_column do
    original_inheritance_column + "_id"
  end
end


587
588
589
# File 'lib/active_record/base.rb', line 587

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


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

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


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

def set_table_name( value=nil, &block )
  define_attr_method :table_name, value, &block
end

.silenceObject

Silences the logger for the duration of the block.



674
675
676
677
678
679
680
# File 'lib/active_record/base.rb', line 674

def silence
  result = nil
  logger.level = Logger::ERROR
  result = yield
  logger.level = Logger::DEBUG
  return result
end

.sqlite3_connection(config) ⇒ Object

sqlite3 adapter reuses sqlite_connection.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 11

def sqlite3_connection(config) # :nodoc:
  parse_config!(config)

  unless self.class.const_defined?(:SQLite3)
    require_library_or_gem(config[:adapter])
  end

  db = SQLite3::Database.new(
    config[:dbfile],
    :results_as_hash => true,
    :type_translation => false
  )
  ConnectionAdapters::SQLiteAdapter.new(db, logger)
end

.sqlite_connection(config) ⇒ Object

Establishes a connection to the database that’s used by all Active Record objects



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 27

def sqlite_connection(config) # :nodoc:
  parse_config!(config)

  unless self.class.const_defined?(:SQLite)
    require_library_or_gem(config[:adapter])

    db = SQLite::Database.new(config[:dbfile], 0)
    db.show_datatypes   = "ON" if !defined? SQLite::Version
    db.results_as_hash  = true if defined? SQLite::Version
    db.type_translation = false

    # "Downgrade" deprecated sqlite API
    if SQLite.const_defined?(:Version)
      ConnectionAdapters::SQLiteAdapter.new(db, logger)
    else
      ConnectionAdapters::DeprecatedSQLiteAdapter.new(db, logger)
    end
  end
end

.sqlserver_connection(config) ⇒ Object

:nodoc:



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/active_record/connection_adapters/sqlserver_adapter.rb', line 13

def self.sqlserver_connection(config) #:nodoc:
  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.



142
143
144
# File 'lib/active_record/connection_adapters/abstract_adapter.rb', line 142

def self.symbolize_strings_in_hash(hash) #:nodoc:
  hash.symbolize_keys
end

.table_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 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
   table_name "mice"
end


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

def table_name
  table_name_prefix + undecorated_table_name(class_name_of_active_record_descendant(self)) + table_name_suffix
end

.timestamps_gmtObject

:nodoc:



55
56
57
58
# File 'lib/active_record/timestamp.rb', line 55

def self.timestamps_gmt #:nodoc:
  warn "timestamps_gmt is deprecated. use default_timezone instead"
  self.default_timezone == :utc
end

.timestamps_gmt=(gmt) ⇒ Object

:nodoc:



50
51
52
53
# File 'lib/active_record/timestamp.rb', line 50

def self.timestamps_gmt=( 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.



386
387
388
389
390
391
392
393
394
395
# File 'lib/active_record/base.rb', line 386

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


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

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

Instance Method Details

#==(comparison_object) ⇒ Object

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



1053
1054
1055
# File 'lib/active_record/base.rb', line 1053

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



998
999
1000
# File 'lib/active_record/base.rb', line 998

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



1004
1005
1006
# File 'lib/active_record/base.rb', line 1004

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.



1043
1044
1045
# File 'lib/active_record/base.rb', line 1043

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)


1037
1038
1039
1040
# File 'lib/active_record/base.rb', line 1037

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.



1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
# File 'lib/active_record/base.rb', line 1024

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.



1013
1014
1015
1016
1017
1018
1019
1020
1021
# File 'lib/active_record/base.rb', line 1013

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.



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

def clone
  attrs = self.attributes
  attrs.delete(self.class.primary_key)
  cloned_record = self.class.new(attrs)
  cloned_record
end

#column_for_attribute(name) ⇒ Object

Returns the column object for the named attribute.



1048
1049
1050
# File 'lib/active_record/base.rb', line 1048

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.



228
229
230
# File 'lib/active_record/base.rb', line 228

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.



966
967
968
969
970
# File 'lib/active_record/base.rb', line 966

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

#decrement!(attribute) ⇒ Object

Decrements the attribute and saves the record.



973
974
975
# File 'lib/active_record/base.rb', line 973

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



918
919
920
921
922
923
924
925
926
927
928
# File 'lib/active_record/base.rb', line 918

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)


1058
1059
1060
# File 'lib/active_record/base.rb', line 1058

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


1064
1065
1066
# File 'lib/active_record/base.rb', line 1064

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.



888
889
890
# File 'lib/active_record/base.rb', line 888

def id
  read_attribute(self.class.primary_key)
end

#id=(value) ⇒ Object

Sets the primary ID.



901
902
903
# File 'lib/active_record/base.rb', line 901

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

#id_before_type_castObject

:nodoc:



892
893
894
# File 'lib/active_record/base.rb', line 892

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.



954
955
956
957
958
# File 'lib/active_record/base.rb', line 954

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

#increment!(attribute) ⇒ Object

Increments the attribute and saves the record.



961
962
963
# File 'lib/active_record/base.rb', line 961

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

#locking_enabled?Boolean

:nodoc:

Returns:

  • (Boolean)


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

def locking_enabled? #:nodoc:
  lock_optimistically && respond_to?(:lock_version)
end

#new_record?Boolean

Returns true if this object hasn’t been saved yet – that is, a record for the object doesn’t exist yet.

Returns:

  • (Boolean)


906
907
908
# File 'lib/active_record/base.rb', line 906

def new_record?
  @new_record
end

#quoted_idObject

:nodoc:



896
897
898
# File 'lib/active_record/base.rb', line 896

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

#reloadObject

Reloads the attributes of this object from the database.



989
990
991
992
993
# File 'lib/active_record/base.rb', line 989

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)


1073
1074
1075
# File 'lib/active_record/base.rb', line 1073

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



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

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.



912
913
914
# File 'lib/active_record/base.rb', line 912

def save
  create_or_update
end

#toggle(attribute) ⇒ Object

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



978
979
980
981
# File 'lib/active_record/base.rb', line 978

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

#toggle!(attribute) ⇒ Object

Toggles the attribute and saves the record.



984
985
986
# File 'lib/active_record/base.rb', line 984

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.



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

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.



948
949
950
951
# File 'lib/active_record/base.rb', line 948

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