【问题标题】:ActiveRecord query for child objects in BEFORE_SAVE callback in RubyRuby 中 BEFORE_SAVE 回调中子对象的 ActiveRecord 查询
【发布时间】:2016-09-18 21:43:24
【问题描述】:

TypeLogisticOrder 的子级

我在Order 上有一个before_save 回调。在那个before_save 回调中,我需要根据Order 是否有特定的子TypeLogistic 来采取不同的操作。

代码:

class Order

  before_save :do_something

  def do_something
    if self.type_logistics.where(type_of_logistics:"this type").present?
      ...
      # something that uses the data in the child type_logistic
    else 
      ...
    end
  end
end

这有可能吗?只是在玩控制台:

o = Order.new({"type_logistics_attributes" => [{"type_of_logistics" => "this_type}]})
o.type_logistics
=> #<ActiveRecord::Associations::CollectionProxy [#<TypeLogistic id: nil, type_of_logistics: "this type" >]> 
o.type_logistics.where(type_of_logistics:"delivery")
=> #<ActiveRecord::AssociationRelation []>

我想既然控制台的第二个语句返回了一些东西,那么也许有办法让第三个控制台也返回?


如果这完全不可能,我愿意接受其他建议。其他一些上下文:

  1. 我不能真正使用after_commit,因为do_something 方法中有一些东西需要通过ActiveRecord::Dirty 检测new_record?attribute_changed?,而这不起作用after_commit

  2. 顺便说一句,after_save 应该可以工作,因为它可以让我对attribute_changed? 进行上述检测,同时还给我可以使用的对象 ID,但在生产中我发现它没有。也许是因为do_something 包含在不同线程上操作的延迟作业,并且找不到所需的记录或其他什么

这就是我试图让before_save 工作的原因。如果无法找到子对象,我只需解析所需子对象属性的参数即可。没什么大不了的,只是不会这么简单。

【问题讨论】:

    标签: ruby-on-rails ruby activerecord callback


    【解决方案1】:

    我的建议:不要使用回调,使用某种服务对象来负责保存该订单。 回调将变得混乱且难以调试、测试和维护。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      相关资源
      最近更新 更多