Instance Public methods
create(attributes = nil, &block)

Creates an object (or multiple objects) and saves it to the database, if validations pass. The resulting object is returned whether the object was saved successfully to the database or not.

The attributes parameter can be either a Hash or an Array of Hashes. These Hashes describe the attributes on the objects that are to be created.


# Create a single new object
User.create(first_name: 'Jamie')

# Create an Array of new objects
User.create([{ first_name: 'Jamie' }, { first_name: 'Jeremy' }])

# Create a single object and pass it into a block to set other attributes.
User.create(first_name: 'Jamie') do |u|
  u.is_admin = false

# Creating an Array of new objects using a block, where the block is executed for each object:
User.create([{ first_name: 'Jamie' }, { first_name: 'Jeremy' }]) do |u|
  u.is_admin = false
# File activerecord/lib/active_record/persistence.rb, line 29
def create(attributes = nil, &block)
  if attributes.is_a?(Array)
    attributes.collect { |attr| create(attr, &block) }
    object = new(attributes, &block)
instantiate(attributes, column_types = {})

Given an attributes hash, instantiate returns a new instance of the appropriate class. Accepts only keys as strings.

For example, Post.all may return Comments, Messages, and Emails by storing the record's subclass in a type attribute. By calling instantiate instead of new, finder methods ensure they get new instances of the appropriate class for each record.

See +ActiveRecord::Inheritance#discriminate_class_for_record+ to see how this “single-table” inheritance mapping is implemented.

# File activerecord/lib/active_record/persistence.rb, line 49
def instantiate(attributes, column_types = {})
  klass = discriminate_class_for_record(attributes)
  column_types = klass.decorate_columns(column_types.dup)
  klass.allocate.init_with('attributes' => attributes, 'column_types' => column_types)