简体   繁体   English

Rails 模型:如何在保存之前计算(使用过滤器)嵌套实体

[英]Rails model: How to count (with filter) nested entities before saving

I have a parent entity that contains children entities which are all created at the same time through nested attributes.我有一个父实体,其中包含所有通过嵌套属性同时创建的子实体。 On the parent entity, I have a callback before save that computes some data to store, based on the nested items.在父实体上,我在保存之前有一个回调,它根据嵌套项计算要存储的一些数据。 The problem is that count triggers a request to the database but entities don't exist yet so it returns 0. If it was just about counting, I'd use the size property, but I need to filter what I count on stuff itself computed in a callback... What's the best solution?问题是count触发了对数据库的请求,但实体尚不存在,所以它返回 0。如果它只是关于计数,我会使用size属性,但我需要过滤我计算的东西本身在回调中......最好的解决方案是什么? See the example below.请参阅下面的示例。

PS: I know about counter_cache for the count but since I only create children through the parent, I prefer to compute it only once at the same time as the other property I compute. PS:我知道counter_cache的计数,但由于我只通过父级创建子级,我更喜欢在计算其他属性的同时只计算一次它。

class Parent < ApplicationRecord
  has_many :children
  accepts_nested_attributes_for :children

  before_save :update_total

  private

  def update_total
    self.total = children.size # OK, this works
    self.total_success = children.count(&:result) # Always 0 since it queries the DB
  end
end
class Child < ApplicationRecord
  belongs_to :parent

  before_save :update_result

  private

  def update_result
    self.result = check_result
  end
end

For now, I've found something that works: the children before save callback is called before the parent's one.现在,我发现了一些有用的东西: before save回调之前的子级在父级之前调用。 I don't feel it's great but at least understandable.我觉得不是很好,但至少可以理解。

I update the total_result this way:我这样更新total_result

self.total_success = 0
children.each { |child| self.total_success += 1 if child.result }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM