Ruby on rails 在保存模型之前,访问所有关联,包括嵌套属性

Ruby on rails 在保存模型之前,访问所有关联,包括嵌套属性,ruby-on-rails,nested-attributes,cocoon-gem,Ruby On Rails,Nested Attributes,Cocoon Gem,我有一个订单、一个项目和一个产品型号 class Order < ApplicationRecord has_many :items, dependent: :destroy, inverse_of: :order end class Item < ApplicationRecord belongs_to :order belongs_to :product end class Product < ApplicationRecord has_many :it

我有一个
订单
、一个
项目
和一个
产品
型号

class Order < ApplicationRecord
  has_many :items, dependent: :destroy, inverse_of: :order
end

class Item < ApplicationRecord
  belongs_to :order
  belongs_to :product
end

class Product < ApplicationRecord
  has_many :items
end
但是,我是这么说的,它只是计算持久化项


不知道这是否重要,但我正在使用@nathanvda管理创建/编辑表单上的嵌套属性。

尝试使用
self.items.collect
。这应该行得通。此外,我建议您在循环中使用
除非item.marked\u for\u destruction?

您想实现什么?看起来好像没有遵循惯例。如果只给你持久化的项目,你也可以使用
after\u save
,如果我的用户在
after\u save
回调进行计算,然后保存订单,它将触发一个无限循环。我要设置订单中订购的箱子总数,单位存储在Item model中,单位存储在de product model中。请尝试使用self.items.collect。这应该行得通。此外,我建议您使用除非item.marked\u用于销毁?在循环内部。同时在:[:创建,:更新]上使用也没有多大意义。在保存之前,回调会自动忽略“on”参数。我建议您在创建之前和更新之前使用回调。@Akshay
.collect
效果很好。请将您的评论作为回答予以接受。
before_save :calculate_boxes, on: [:create, :update]

def calculate_boxes
  self.boxes = 0
  self.items.each do |item|
    self.boxes += item.units / item.product.units_per_box
  end
end