通过关联对 has_many 实现软删除的最简单方法是什么?
我想要的是这样的:
class Company > ActiveRecord::Base
has_many :staffings
has_many :users, through: :staffings, conditions: {staffings: {active: true}}
end
我想按以下方式使用 Company#users
:
Company#users
应该是一个正常的关联,以便它与表单一起工作并且不会破坏现有契约(Contract)。- 向公司添加用户时,会创建一个
active: true
的新Staffing
。 - 从公司删除用户时,现有的
Staffing
会更新active: false
(目前它只是被删除). - 将先前删除的用户添加到公司时(以便
Staffing#active == false
),Staffing
更新为active: true
.
我考虑过覆盖 Company#users=
方法,但它确实不够好,因为还有其他更新关联的方法。
所以问题是:如何在 Company#users
关联上实现解释的行为?
谢谢。
最佳答案
has_many :through
关联实际上只是语法糖。当你需要做繁重的工作时,我会建议拆分逻辑并提供适当的方法和范围。了解如何覆盖 callbacks对这类事情也很有用。
这将使您开始对 User
进行软删除,并在 User
之后创建 Staffings
class Company < ActiveRecord::Base
has_many :staffings
has_many :users, through: :staffings, 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
关于ruby-on-rails - 通过关联软删除 has_many,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10441633/