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?

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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

2 Comments

If you know what you are about, you might just want to go with raw SQL, that'll enable you to craft your SQL to be exactly what you want.
How do you skip a particular validation?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.