Rails 3.2:销毁元素时也会调用 after_update 吗?
我们有一个小班级,有一个相关的班级
class Car
has_one :engine, :dependent => :destroy
after_update :save_engine
delegate :oil_level, :oil_level=, :to => :engine
def save_engine
engine.save if engine
end
end
正如您所知,我们正在尝试解决孩子不会自动保存在 Rails 中的问题。所以我们可以在汽车上设置oil_level
,保存时它会正确地将其存储在engine
中。
现在,当我们尝试删除汽车时会发生什么?显然,engine
永远不会被删除,这是由 after_update
引起的,它将重新保存刚刚删除的引擎。所以汽车被成功删除,但引擎被重新创建(一个新的 ID),并且不再链接到汽车。我希望引擎被正确删除。
我确实找到了一个可靠的解决方法:
class Car
has_one :engine, :dependent => :destroy
after_update :save_engine
before_destroy :set_destroying
delegate :oil_level, :oil_level=, :to => :engine
def set_destroying
@destroying = true
end
def save_engine
engine.save if engine && !@destroying
end
end
但它仍然感觉有点脏,就像应该有更好的方法来做到这一点。 销毁时调用 after_update
似乎有点不合逻辑。 是否有特定的轨道方式来了解回调中实际正在进行的操作(保存/创建/销毁)?
简而言之:处理这个问题的正确方法是什么?或者这实际上是某种 Rails 错误?或者这是有意的行为?
We have small class, that has a related class
class Car
has_one :engine, :dependent => :destroy
after_update :save_engine
delegate :oil_level, :oil_level=, :to => :engine
def save_engine
engine.save if engine
end
end
As you can tell, we are trying to work-around the problem that childs are not automatically saved in rails. So we can set the oil_level
on car, and it will store it in engine
correctly when saving.
Now what happens when we try to delete the car? Apparently the engine
is never deleted, and this is caused by the after_update
which will re-save the just deleted engine. So the car is succesfully deleted, but the engine is recreated (a new id), and no longer linked to a car. I want the engine to be deleted correctly.
I did find a solid work-around:
class Car
has_one :engine, :dependent => :destroy
after_update :save_engine
before_destroy :set_destroying
delegate :oil_level, :oil_level=, :to => :engine
def set_destroying
@destroying = true
end
def save_engine
engine.save if engine && !@destroying
end
end
But it still feels a bit dirty, like there should be a better way to do this.
It seems a bit unlogical that after_update
is called when destroying.
Is there a specific rails-way to know what action is actually in progress in a callback (saving/creating/destroying) ?.
In short: what is the proper way to handle this? Or is this actually some kind of rails-bug? Or is this intended behaviour?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有一段时间没有使用 Rails,所以我可能偏离主题,但是您是否考虑过使用
:autosave
选项?Haven't done Rails for a while, so I may be off topic, but have you considered using the
:autosave
option?1) 确保在 car_controller def destroy 中调用 car.destroy 而不是 car.delete,否则回调将被错过并且引擎不会被销毁。
2)引擎是否没有被删除(相同的id)或正在重新创建? (diff id),您似乎在描述中从一个跳到另一个。
1) make sure that in car_controller def destroy calls car.destroy NOT car.delete, or the callback will be missed and engine won't be destroyed.
2) is the engine not being deleted (same id) or being recreated? (diff id), you seem to jump from one to the other in your description.