是否可以在 Mongo DB 中对批量插入进行验证?
我正在使用 Mongoid 在表上执行批量插入,其中批处理是哈希数组:
@state = State.new
@state.collection.insert batch
我是否通过这样做绕过了 Activerecord?当我尝试验证记录时没有任何反应。
validates_format_of :population, :with => /\d+/
我还尝试执行回调来格式化数据。
before_validation :generate_population
但什么也没发生。
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 try 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的猜测是肯定的。在 Grails 驱动程序中,当您使用集合时,也会发生同样的情况。当你执行 .collection 时,它会绕过普通的 GORM。似乎同样的事情也会发生在 Rails 中。
解决方法是迭代批处理并调用 Rails 中存在的任何验证函数。在 Grails 中你会这样做: new State(it).valid();在 Ruby 中,它可能类似于batch.each { |it| State.new(it).valid }
那么问题是,如果无效,你该怎么办?
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.