Clear ORM
  • Welcome to Clear
  • Introduction
    • Setup
  • Model
    • Defining your model
      • Describing your columns
      • Primary Keys
      • Converters
    • Associations
      • belongs_to
      • has_many
      • has_many through
      • has_one
    • Lifecycle
      • Persistence
      • Validations
      • Triggers
    • Batchs operations
      • Bulk update
      • Bulk insert & delete
    • Transactions & Save Points
      • Transaction & Savepoints
      • Connection pool
    • Locks
  • Querying
    • The collection object
      • Filter the query
        • Filter the query – The Expression Engine
        • Find, First, Last, Offset, Limit
        • Aggregation
        • Ordering & Group by
      • Fetching the query
        • Each and Fetch
        • Cursored fetching
        • Model extra attributes
      • Joins
      • Eager Loading
      • Window and CTE
      • Scopes
    • Writing low-level SQL
      • Select Clause
      • Insert Clause
      • Delete Clause
  • Migrations
    • Manage migrations
    • Call migration script
    • Migration CLI
  • Additional and advanced features
    • JSONB
    • Symbol vs String
    • Enums
    • BCrypt
    • Full Text Search
    • Handling multi-connection
  • Other resources
    • API Documentation
    • Inline documentation
    • Github repository
    • Credits
    • Benchmark
Powered by GitBook
On this page
  1. Model
  2. Batchs operations

Bulk insert & delete

You can insert multiple models at the same time (using just one INSERT query) using the Collection#import method:

u = User.new({id: 1, first_name: "x"})
u2 = User.new({id: 2, first_name: "y"})
u3 = User.new({id: 3, first_name: "z"})

o = User.import([u, u2, u3])

Only non-persisted valid models can be inserted. Any validation failure in the model list will throw an exception and revert the whole process.

Collection#import allows the passing optional block to refine he insert query built:

User.import([u, u2, u3]) do |request| 
  request.on_conflict("(id)").do_update { |upd|
    upd.set("id = NULL")
       .where { users.id == excluded.id }
  }
end
PreviousBulk updateNextTransactions & Save Points

Last updated 6 years ago