Is validation possible in Mongo DB on a batch insert?
I am performing a batch insert on a table using Mongoid where batch is an array of hashes:
@state = State.new
@state.collection.insert batch
Am I bypassing Activerecord by doing it this way? When I t开发者_运维问答ry to validate a record nothing happens.
validates_format_of :population, :with => /\d+/
I'm also trying to perform a callback to format the data.
before_validation :generate_population
And nothing happens.
My guess is yes. In the Grails driver the same thing happens when you use collection. It bypasses the normal GORM when you do .collection. Seems like the same thing would happen in Rails.
A work around would be to iterate over batch and call whatever validate function exists in rails. In Grails you'd do: new State(it).valid(); in Ruby it's likely something like batch.each { |it| State.new(it).valid }
The question is then what should you do if one isn't valid?
Most efficient way to format a hash of data?
This is how I ended up dealing with this problem. I specify formatting functions in the question that I linked, but validation functionality can be added there too.
精彩评论