module ActiveRecord::Persistence::ClassMethods
def create(attributes = nil, &block)
u.is_admin = false
User.create([{ first_name: 'Jamie' }, { first_name: 'Jeremy' }]) do |u|
# Creating an Array of new objects using a block, where the block is executed for each object:
end
u.is_admin = false
User.create(first_name: 'Jamie') do |u|
# Create a single object and pass it into a block to set other attributes.
User.create([{ first_name: 'Jamie' }, { first_name: 'Jeremy' }])
# Create an Array of new objects
User.create(first_name: 'Jamie')
# Create a single new object
==== Examples
in the +options+ parameter.
+create+ respects mass-assignment security and accepts either +:as+ or +:without_protection+ options
attributes on the objects that are to be created.
The +attributes+ parameter can be either a Hash or an Array of Hashes. These Hashes describe the
The resulting object is returned whether the object was saved successfully to the database or not.
Creates an object (or multiple objects) and saves it to the database, if validations pass.
def create(attributes = nil, &block) if attributes.is_a?(Array) attributes.collect { |attr| create(attr, &block) } else object = new(attributes, &block) object.save object end end
def discriminate_class_for_record(record)
See +ActiveRecord::Inheritance#discriminate_class_for_record+ for
record instance.
Called by +instantiate+ to decide which class to use for a new
def discriminate_class_for_record(record) self end
def instantiate(record, column_types = {})
See +ActiveRecord::Inheritance#discriminate_class_for_record+ to see
instances of the appropriate class for each record.
+instantiate+ instead of +new+, finder methods ensure they get new
by storing the record's subclass in a +type+ attribute. By calling
For example, +Post.all+ may return Comments, Messages, and Emails
the appropriate class.
Given an attributes hash, +instantiate+ returns a new instance of
def instantiate(record, column_types = {}) klass = discriminate_class_for_record(record) column_types = klass.decorate_columns(column_types.dup) klass.allocate.init_with('attributes' => record, 'column_types' => column_types) end