7

I am doing a bulk insert where I keep track of the unique columns myself to avoid the m log n insertion cost. Is there a way to disable a validation in code for the life if the method?

user1130176
  • 1,772
  • 1
  • 23
  • 33

2 Answers2

16

one way to do that

new_car=Car.new(...)

new_car.save(validate: false)

other way to use that

Model.skip_callback(:create) 

to remove that and apply it back

Model.set_callback(:create)
Nitin Jain
  • 3,053
  • 2
  • 24
  • 36
  • Doesn't make any difference on Rails 5.1. Still `::create!` raises a validaiton error. Actually my issue is that if I put `config load_defaults 5.1` in `application.rb`, then db seeding fails because of validation errors. And without this call, there are no validation errors. – akostadinov Aug 18 '21 at 18:11
1

I think you might be looking for update_column: http://apidock.com/rails/ActiveRecord/Persistence/update_column

or Rails 4 update_columns: http://api.rubyonrails.org/v4.0.2/classes/ActiveRecord/Persistence.html#method-i-update_columns

And here is some info from the guides about skipping validations: http://edgeguides.rubyonrails.org/active_record_validations.html#skipping-validations

Or you can use update_all to change the same column on many records at once: http://apidock.com/rails/ActiveRecord/Relation/update_all , Rails 4 docs: http://api.rubyonrails.org/v4.0.2/classes/ActiveRecord/Relation.html#method-i-update_all

Or you could just execute the raw SQL using execute (Rails 4 docs): http://api.rubyonrails.org/v4.0.2/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#method-i-execute , here is a StackOverflow question about doing this: Rails raw SQL example and here is another one: Rails 3, custom raw SQL insert statement

Community
  • 1
  • 1
RustyToms
  • 7,600
  • 1
  • 27
  • 36