Method: ActiveRecord::Base#initialize

Defined in:
activerecord/lib/active_record/base.rb

#initialize(attributes = nil, options = {}) {|_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.

initialize respects mass-assignment security and accepts either :as or :without_protection options in the options parameter.

Examples

# Instantiates a single new object
User.new(:first_name => 'Jamie')

# Instantiates a single new object using the :admin mass-assignment security role
User.new({ :first_name => 'Jamie', :is_admin => true }, :as => :admin)

# Instantiates a single new object bypassing mass-assignment security
User.new({ :first_name => 'Jamie', :is_admin => true }, :without_protection => true)

Yields:

  • (_self)

Yield Parameters:



1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
# File 'activerecord/lib/active_record/base.rb', line 1549

def initialize(attributes = nil, options = {})
  @attributes = attributes_from_column_definition
  @association_cache = {}
  @aggregation_cache = {}
  @attributes_cache = {}
  @new_record = true
  @readonly = false
  @destroyed = false
  @marked_for_destruction = false
  @previously_changed = {}
  @changed_attributes = {}
  @relation = nil

  ensure_proper_type
  set_serialized_attributes

  populate_with_current_scope_attributes

  assign_attributes(attributes, options) if attributes

  yield self if block_given?
  run_callbacks :initialize
end