Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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' }
])
like image 944
João Souza Avatar asked Dec 15 '22 04:12

João Souza


1 Answers

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.

like image 66
João Souza Avatar answered Jan 21 '23 15:01

João Souza