ruby-on-rails – 通过关联对has_many进行软删除

通过关联在has_many上实现软删除的最简单方法是什么?

我想要的是这样的:

class Company > ActiveRecord::Base
  has_many :staffings
  has_many :users,through: :staffings,conditions: {staffings: {active: true}}
end

我想通过以下方式使用Company#users:

>公司#用户应该是正常的关联,以便它与表格一起使用,并且不会破坏现有合同.
>将用户添加到公司时,会创建一个具有active:true的新Staffing.
>从公司中删除用户时,现有人员配置将更新为活动:false(当前只是被删除).
>将以前删除用户添加到公司时(以便Staffing #active == false),Staffing将更新为active:true.

我考虑过覆盖公司#useuse =方法,但它确实不够好,因为还有其他更新关联的方法.

所以问题是:如何在公司#用户协会上实现解释的行为?

谢谢.

解决方法

has_many:通过关联实际上只是语法糖.当你需要做繁重的工作时,我会建议拆分逻辑并提供适当的方法和范围.了解如何覆盖 callbacks对于此类事情也很有用.

这将使您开始在用户上进行软删除并在用户之后创建人员配置

class Company < ActiveRecord::Base
  has_many :staffings
  has_many :users,conditions: ['staffings.active = ?',true]
end

class Staffing < ActiveRecord::Base
  belongs_to :company
  has_one :user
end

class User < ActiveRecord::Base
  belongs_to :staffing

  # after callback fires,create a staffing
  after_create {|user| user.create_staffing(active: true)}

  # override the destroy method since you 
  # don't actually want to destroy the User
  def destroy
    run_callbacks :delete do
      self.staffing.active = false if self.staffing
    end
  end
end

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...