Create Records

This guide shows you how to create new records in the database.

Create with new + save

Create an instance and save separately:

user = User.new("John", "john@example.com")

if user.save
  puts "Created user #{user.id}"
else
  puts "Failed: #{user.errors.map(&.message).join(", ")}"
end

Create with save!

Use save! to raise an exception on failure:

user = User.new("John", "john@example.com")
user.save!  # Raises if validation fails
puts "Created user #{user.id}"

Create in One Step

Use create to instantiate and save:

Create! in One Step

Use create! to raise on failure:

Create Multiple Records

Create with Relationships

Create with Default Values

Set defaults in your model:

Create with Timestamp

Timestamps are set automatically if configured:

Handle Validation Errors

Verify Creation

Last updated

Was this helpful?