【发布时间】:2016-09-18 21:43:24
【问题描述】:
TypeLogistic 是Order 的子级
我在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 []>
我想既然控制台的第二个语句返回了一些东西,那么也许有办法让第三个控制台也返回?
如果这完全不可能,我愿意接受其他建议。其他一些上下文:
我不能真正使用
after_commit,因为do_something方法中有一些东西需要通过ActiveRecord::Dirty检测new_record?或attribute_changed?,而这不起作用after_commit顺便说一句,
after_save应该可以工作,因为它可以让我对attribute_changed?进行上述检测,同时还给我可以使用的对象 ID,但在生产中我发现它没有。也许是因为do_something包含在不同线程上操作的延迟作业,并且找不到所需的记录或其他什么
这就是我试图让before_save 工作的原因。如果无法找到子对象,我只需解析所需子对象属性的参数即可。没什么大不了的,只是不会这么简单。
【问题讨论】:
标签: ruby-on-rails ruby activerecord callback