【发布时间】:2019-01-20 19:02:49
【问题描述】:
首先,我想做的是 - 我有一些传入参数可能相当大,用于更新服务器上的对象(有时大约 500 个对象的属性值可能是正常的)。
我的逻辑是这样的:
def create_objects(object_attribute_array)
errors = []
return if object_attribute_array.blank?
# Client ids are generated on clients to help with objects that were actually already created on the server but not returned due to faulty network connections
incoming_client_ids = object_attribute_array.pluck(:client_id)
existing_objects = current_user.objects.where(client_id: incoming_client_ids)
# commit array in transaction - if after_rollback, error panic mode
object_attribute_array.each do |obj|
if existing_objects.pluck(:client_id).include?(obj[:client_id])
# update it conditionally based on update time by changing the incoming object parameters but do not save
else
# create, validate, add to transaction
end
end
end
那么,我想做什么(我想?):
从逻辑上讲,我会首先获取现有对象,使用传入参数覆盖任何现有对象信息,但不要将对象保存到数据库中。只需验证它,然后将其保存在经过验证的对象数组中。 然后,新建并验证不存在的对象,并将这些对象也添加到数组中。由于理论上将所有对象保存在数组中会顺利进行,所以我应该将它包装在一个事务中以进行单个数据库调用?
或者我是否应该尝试简单地一个一个地保存数组对象,以便返回单个对象错误但数据库事务不会回滚?
非常感谢任何帮助,我已经阅读了很多关于事务的内容并且熟悉它们的工作方式,但是我没有看到很多关于验证 -> 添加到内存中的数组 -> 持久化的最佳实践。
【问题讨论】:
标签: ruby-on-rails postgresql validation ruby-on-rails-5