Rails:依赖 =>销毁,想要调用另一个操作而不是销毁
我有一个运行良好的 has_many :through 模型。
has_many :varietals
has_many :grapes, :through => :varietals, :dependent => :destroy
我想调用另一个操作而不是:destroy。事实上,我不想使该项目无效或销毁它,我想将记录状态字段从 1 更新为 0,而不是销毁记录。
如何调用自定义方法而不是 destroy ?我想我可以在模型本身中做到这一点......谢谢。
这个方法该放在哪里呢?在主模型或模型里的记录会被破坏吗?
编辑:
很抱歉,但我认为我没有充分解释我的问题。我的问题不仅仅是主模型被破坏后的事情。我想在 Varietal 模型本身中自定义销毁操作,即使主记录没有被销毁。
比如:
class Varietal < ActiveRecord::Base
private
def destroy
self.update_attributes(:status => 0)
end
end
实际上这个动作不叫......
I have a has_many :through model that works perfectly.
has_many :varietals
has_many :grapes, :through => :varietals, :dependent => :destroy
I would like to call another action instead of :destroy. In fact, I don't want to nullify the item OR destroy it, I want to update the record status field from 1 to 0 instead of destroy the record.
How to call a custom method instead of destroy ? I suppose I can do that in the model itself... Thanks.
Where to put this method ? In the master model or in the model where the record will be destroyed ?
EDIT:
I'm sorry but I think I didn't enough explain my problem. My problem is not only to so something after the master model is destroyed. I want to custom the destroy action in the Varietal model itself even if the master record is not destroyed.
Something like:
class Varietal < ActiveRecord::Base
private
def destroy
self.update_attributes(:status => 0)
end
end
Actually this action is not called...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 before_destroy 将自定义逻辑放在那里。例如,
请查看此处了解更多详细信息。
You can use before_destroy to put your custom logic there. E.g.,
Check here for more details.
您只需要在 before_destroy 或 after_destroy 上添加回调并操作您的关联。举例来说
You just need add a callback on before_destroy or after_destroy and manipulate your associations. By example
has_many :dependent 仅限于几个选项。根据文档:
看起来您需要更改 destroy 方法来更新状态字段。
has_many :dependent is limited to only a few options. According to the documentation:
It looks like you would need to alter the destroy method to update the status field.
我相信解决您的问题的好方法是提供自定义销毁方法。对于此类问题有多种回答,但您应该记住 ActiveRecord 和关系,例如:
也使用触发破坏链接到您的关系的回调机制。通常您应该保留此机制并将其添加到您的自定义实现中。例如
,您也可以阅读这篇文章:
使用覆盖的 destroy-method 触发 dependent: :destroy
I believe that good approach to solve your problem is to provide a custom destroy method. There are several responses to questions like these, but you should keep in mind that ActiveRecord and Relationships like:
use callback mechanisms that trigger destroy chaining to your relations, too. Usually you should preserve this mechanism and add it to your custom implementation. E.g.
You can read this post, too:
Triggering dependent: :destroy with overridden destroy-method