Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically disable rails validation ?

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?

like image 410
user1130176 Avatar asked Dec 28 '13 15:12

user1130176


2 Answers

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)
like image 117
Nitin Jain Avatar answered Nov 01 '22 21:11

Nitin Jain


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

like image 28
RustyToms Avatar answered Nov 01 '22 20:11

RustyToms