João Souza
João Souza

Reputation: 4218

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' }
])

Upvotes: 6

Views: 7498

Answers (3)

user2553863
user2553863

Reputation: 780

At least since rails 7.2.2.1, there is an ActiveRecord method named upsert_all that seems to be exactly what you are looking for. It's useful for instance, for importing datasets from other sources (like csv or ods) when you don't want to apply validations nor callbacks.

From the link, you could use it like this:

Commodity.upsert_all(
  [
    { id: 2, name: "Copper", price: 4.84 },
    { id: 4, name: "Gold", price: 1380.87 },
    { id: 6, name: "Aluminium", price: 0.35 }
  ]
)

There also is a single-record method named upsert.

Upvotes: 0

João Souza
João Souza

Reputation: 4218

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.

Upvotes: 7

Michał Młoźniak
Michał Młoźniak

Reputation: 5556

You can't do that with create. If you really must skip validations you can do something like this:

[
  { name: 'Apps' },
  { name: 'Songs' },
  { name: 'Movies' }
].each do |attributes|
  c = Category.new(attributes)
  s.save(validate: false)
end

Upvotes: 5

Related Questions