method

create

rails latest stable - Class: ActiveRecord::Base

Method deprecated or moved

This method is deprecated or moved on the latest stable version. The last existing version (v3.1.0) is shown here.

create(attributes = nil, options = {}, &block)
public

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 be a Hash or an Array of Hashes. These Hashes describe the attributes on the objects that are to be created.

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

Examples

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

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

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

# 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
end

# 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
end

3Notes

yijisoo

sfusion · Dec 13, 20091 thank

create generates the object and saves. new only generates the object.

e.g.

o = Object.new(:foo => 'bar')
o.save

is the same as

o = Object.create(:foo => 'bar')

What's difference between create and new?

yijisoo · Dec 13, 2009

What's difference between create and new?

Where this method moved to

roryokane · May 25, 2016

After v3.1.0, this method moved to ActiveRecord::Persistence::ClassMethods#create .