在Rails STI中从一个子类切换到另一个子类的最佳方法是什么

我目前正在使用Rails 5.2.2 我的问题是我的应用程序是Rails API,并且实现了STI,因此我有时必须在对象的 update 上从一个子类切换到另一个子类。

示例代码:

class TestApp < ApplicationRecord
  has_many :admins,dependent: :destroy
  has_one :super_admin,dependent: :destroy
  has_many :users,dependent: :destroy

  accepts_nested_attributes_for :admins,allow_destroy: true
  accepts_nested_attributes_for :users,allow_destroy: true
  accepts_nested_attributes_for :super_admin,allow_destroy: true
end

class User < ApplicationRecord
  has_many :admins
  has_many :super_admins
end

class Admin < User
  belongs_to :user,inverse_of: :admin
  belongs_to :test_app,inverse_of: :admin
  validates_uniqueness_of :employee_id,scope: :test_app_id
end

class SuperAdmin < User
  belongs_to :user,inverse_of: :super_admin
  belongs_to :test_app,inverse_of: :super_admin
end

参考上面的代码,当我创建一个新的TestApp对象时,它可以直接拥有许多用户,或者根据需要具有Admins和Superadmin。

当TestApp对象具有Admins和SuperAdmin时,它可以具有许多Admin,但是只有一个Superadmin,并且在任何时间点,都可以将任何admin设置为superadmin,并且可以将旧的superadmin改回admin,或者在需要时可以将其更改为admin。被删除。

现在,当我想将用于更改和管理的属性发送给超级管理员时,有效负载如下所示:

{ 
  "admins_attributes":[
    { 
      "name":"Virat Kohli","employee_id":"1234567"
    }
  ],"super_admin_attributes":{ 
    "name":"M S Dhoni","emplpyee_id": "7777777"
  }
}

如果在上述更新调用之前,MS Dhoni已经是管理员,而Virat Kohli是超级管理员,那么我应该如何处理更新记录。

PS:目前,我正在修补所有文件,并以非常无轨的方式手动处理记录。

谢谢!

xy080121 回答:在Rails STI中从一个子类切换到另一个子类的最佳方法是什么

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/2901459.html

大家都在问