Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 上的软删除通过关联有多个_Ruby On Rails_Ruby_Activerecord_Orm_Associations - Fatal编程技术网

Ruby on rails 上的软删除通过关联有多个

Ruby on rails 上的软删除通过关联有多个,ruby-on-rails,ruby,activerecord,orm,associations,Ruby On Rails,Ruby,Activerecord,Orm,Associations,通过关联在has上实现软删除的最简单方法是什么 我想要的是这样的东西: class Company > ActiveRecord::Base has_many :staffings has_many :users, through: :staffings, conditions: {staffings: {active: true}} end 我想通过以下方式使用公司#用户: 公司#用户应该是一个正常的关联,这样它就可以使用表单,并且不会破坏现有的合同 将用户添加到公司时,将创

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

我想要的是这样的东西:

class Company > ActiveRecord::Base
  has_many :staffings
  has_many :users, through: :staffings, conditions: {staffings: {active: true}}
end
我想通过以下方式使用
公司#用户

  • 公司#用户
    应该是一个正常的关联,这样它就可以使用表单,并且不会破坏现有的合同
  • 用户添加到公司时,将创建一个新的
    人员配置
    ,其中
    处于活动状态:true
  • 从公司中删除用户时,现有的
    人员编制将更新
    活动:false
    (当前它刚刚被删除
  • 将以前删除的用户添加到公司时(以便
    人员配置#active==false
    ),人员配置将更新为
    active:true
我曾考虑过重写
Company#users=
方法,但它确实不够好,因为还有其他方法可以更新关联

因此问题是:如何在
公司#用户
关联上实现解释行为?


谢谢。

有很多:通过
关联实际上只是语法上的糖分。当您需要执行繁重的工作时,我建议您将逻辑分解,并提供适当的方法和范围。理解如何重写对于这类事情也很有用

这将使您开始在
用户
上进行软删除,并在
用户

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
class公司
我很清楚回调和所有这些。我想你没有读过这个问题。我如何使用我描述的
公司#用户
方法?我的回答没有提供解决方案的四个用例中的哪一个?您可以保留
公司
定义,并在创建
回调后添加
,以及重写的
销毁
方法,您提到的所有功能都应该考虑在内。也许对你打算如何使用
Company#users
进行一些澄清会有所帮助,因为你实际上没有解释你打算如何使用
Company#users
,只是因为它需要满足四个合同。我对这个问题做了一些更新。请花点时间读一下。