【问题标题】:rails4 dependent destroy callback errorrails4 依赖销毁回调错误
【发布时间】:2016-05-23 10:51:54
【问题描述】:

我在ProductUser 模型上有一个role 属性。用户可以通过owner(角色)删除,我想确保所有者在product 存在时不能删除自己。但是,当product 被删除时,所有product_users 都应该消失,包括所有者。

当我尝试删除product 时,以下代码会引发ActiveRecord::RecordNotDestroyed - Failed to destroy the record 错误。我猜这是因为dependent: :destroy 导致的执行顺序。我怎样才能做到这一点?

class ProductUser < ActiveRecord::Base
  belongs_to :user
  belongs_to :product, touch: true

  before_destroy :check_for_owner

  def check_for_owner
    if product && role == "owner" #If I use simply: if role == "owner", it still doesn't work.
      errors[:base] << "Owner can't be deleted!"
      return false
    end
  end
end


class Product < ActiveRecord::Base
  has_many :product_users, dependent: :destroy
  ....
end

【问题讨论】:

    标签: ruby-on-rails validation activerecord callback


    【解决方案1】:

    如果用户是所有者,您是否考虑过不显示 ProductUser 记录的删除按钮?

    在任何情况下,如果您使用外键而不是依赖销毁,那么销毁将在数据库级别发生,并且不会实例化产品用户模型,这将解决您的问题。

    所以在迁移中

    def change
      add_foreign_key :product_users, :products, on_delete: :cascade
    end
    

    然后在产品上删除依赖的销毁选项

    class Product < ActiveRecord::Base
      has_many :product_users
    end
    

    使用 on delete cascade 选项,数据库将在产品被删除时销毁产品的产品用户。

    【讨论】:

    • j-dexx,我没有展示它,但想确保一切正常。我也在使用外键约束,但目前没有级联。顺便提一句。这是最好的解决方案吗?我的意思是我不能只在 rails 中或在 db(级联)和 rails 中都做某事吗?我通常喜欢做双重保护,比如假设有一个必须存在的属性,然后我在 rails 端做validate :attribute, presence: true,在 db 端做null: false
    • 不,我想不到。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-26
    • 2013-01-22
    • 1970-01-01
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多