【问题标题】::dependent => :destroy for a serialized array value:dependent => :destroy 用于序列化数组值
【发布时间】:2015-10-20 11:01:08
【问题描述】:

我有两个模型,

class Event < ActiveRecord::Base
  serialize :user_ids, Array
end

class User < ActiveRecord::Base

end

假设事件模型中的 user_ids 的值为 [1,2,3,4]。

现在,如果我删除 ID 为 1 的用户记录。

它还必须删除驻留在事件表的 user_ids 字段中的 user_id。结果应该是user_ids = [2,3,4]。像 :dependant => :destroy.

我是否需要为此编写 before_destroy 回调确定..?或任何其他解决方案?

【问题讨论】:

    标签: ruby-on-rails serialization


    【解决方案1】:

    是的,正如您所建议的,您必须在自己编写的回调中执行此操作。比如:

    before_destroy :remove_users
    
    def remove_users
      User.where(id: self.user_ids).destroy_all
    end
    

    虽然看起来确实很有破坏性。通常User 用于登录到您系统的用户,但我猜您在这种情况下并没有像那样使用它。

    【讨论】:

    • 谢谢@shadwell.,但是有没有其他最简单的解决方案,比如 :dependant => :destroy 而不是为这种情况编写我们自己的方法..?对不起这个愚蠢的问题。 :P :P
    • 不,很遗憾,您将不得不在此代码上编写自己的代码 - rails/active record 不支持这种情况。
    • 酷.. Thnaks.. :) :)\
    猜你喜欢
    • 2011-02-17
    • 2010-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多