Search code examples
ruby-on-railsactiverecord

ActiveRecord: Skip validation when saving multiple objects


I know I can skip validations for an individual save, like this:

User.new(name: 'John').save(validate: false)

But how can I do that when saving multiple objects at once? Like this:

Category.create([
  { name: 'Apps' },
  { name: 'Songs' },
  { name: 'Movies' }
])

Solution

  • I found this gem: https://github.com/zdennis/activerecord-import

    It works like this:

    categories = [ 
      Category.new(name: 'Apps'),
      Category.new(name: 'Songs'),
      Category.new(name: 'Movies')
    ]
    
    Category.import(categories, validate: false)
    

    It is also possible to use plain arrays instead of ActiveRecord objects.

    I guess it generates pure SQL when validate is set to false so it can skip validations.