ruby-on-rails – 通过关联对has_many进行软删除
发布时间:2020-12-17 02:31:53 所属栏目:百科 来源:网络整理
导读:通过关联在has_many上实现软删除的最简单方法是什么? 我想要的是这样的: class Company ActiveRecord::Base has_many :staffings has_many :users,through: :staffings,conditions: {staffings: {active: true}}end 我想通过以下方式使用Company#users:
通过关联在has_many上实现软删除的最简单方法是什么?
我想要的是这样的: class Company > ActiveRecord::Base has_many :staffings has_many :users,through: :staffings,conditions: {staffings: {active: true}} end 我想通过以下方式使用Company#users: >公司#用户应该是正常的关联,以便它与表格一起使用,并且不会破坏现有合同. 我考虑过覆盖公司#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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |