【问题标题】:Access all associations, including nested attributes, before save model在保存模型之前访问所有关联,包括嵌套属性
【发布时间】:2018-09-25 06:16:35
【问题描述】:

我有一个Order、一个Item 和一个Product 模型。

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

我需要在before_save 回调中计算每个Item 有多少个框(item.units/item.product.units_per_box),但我无法访问嵌套属性,只能访问持久项。

我在Order 模型中有这个:

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

但是,正如我所说,它只是计算持久化的项目。

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

【问题讨论】:

  • 你想完成什么?看起来不遵循惯例。你也可以使用after_save,如果它只为你提供持久化的项目
  • 如果我使用after_save 回调进行计算然后保存订单,它将触发无限循环。我想设置订单中订购的盒子总数,单位存储在Item模型中,每盒单位存储在de product模型中。
  • 尝试使用 self.items.collect。那应该行得通。另外我建议您使用除非 item.marked_for_destruction?在循环内。
  • 同时使用 on: [:create, :update] 没有多大意义。 before_save 回调默默地忽略“on”参数。我建议您改用 before_create 和 before_update 回调。
  • @Akshay .collect 工作得很好。请发表您的评论作为接受它的答案。

标签: ruby-on-rails nested-attributes cocoon-gem


【解决方案1】:

尝试使用self.items.collect。那应该行得通。另外我建议你在循环中使用unless item.marked_for_destruction?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多