如果实体与用户界面中的不同实体相关联,我希望防止删除实体。
class foo
belongs_to bar
class bar
在获取/ foos(即Foo对象的列表)时,我们想以某种方式显示每个foo的bar的数量,用户界面可以使用它作为指示以避免删除Bar实体grater zero
为了防止删除与另一个实体相关联的一个实体,可以使用软删除来完成。在rails中,可以使用acts_as_paranoid gem来实现。
我认为你的例子是错的,你想说的是以下内容:
class foo < ApplicationRecord
has_many :bars
end
class bar < ApplicationRecord
belongs_to :foo
end
如果是这种情况,那么你需要实现一个counter cache。
您的代码将变为:
class bar < ApplicationRecord
belongs_to :foo, counter_cache: true
end
你应该在foo
上添加一个名为bars_count
的列;
现在,每当你创建一个新的foo时,它会自动增加bars_count
;当然,删除foo时减少它。