ActiveRecord: Skip validation when saving multiple objects

无人久伴 提交于 2020-01-03 16:04:13

问题


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

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/39064067/activerecord-skip-validation-when-saving-multiple-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!