【问题标题】:Prevent destruction if HABTM relation isnt empty如果 HABTM 关系不为空,则防止破坏
【发布时间】:2014-01-08 05:49:14
【问题描述】:
    class Annex
      has_and_belongs_to_many: :documents
    end

    class Document
      has_and_belongs_to_many: :annexes
    end 

我想实现这种行为:如果附件与至少一个文档相关联,则不应销毁它。

有没有一种简单的 Rails 方法可以做到这一点,还是我必须解决这个问题?

我是否必须使用 before_destroy 方法或类似的方法?

【问题讨论】:

标签: ruby-on-rails has-and-belongs-to-many


【解决方案1】:

做这样的事情:

class Annex < ActiveRecord::Base
  has_and_belongs_to_many :documents
  before_destroy { raise "Can't destroy Annex, because it's still associated to 1 or more documents" if documents.any? }
end

【讨论】:

  • 我明白了,毕竟 Rails 无法使用关系选项来处理它。但这似乎已经够枯燥了,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多