合并activerecords:has_many具有唯一约束的关联

时间:2019-09-10 04:28:04

标签: activerecord reflection merge ruby-on-rails-5

我正在尝试编写有关ActiveRecord的一般深度合并的问题Mergeable。代码是草稿,可能无法编译;鉴于:

class Faz < ApplicationRecord
  has_many :bar
end

class Bar < ApplicationRecord
  belongs_to :foo
  belongs_to :faz

  # has index :bars, [:foo_id, :faz_id], unique: true
end

class Foo < ApplicationRecord
  include Mergeable
  has_many :bar
  has_many :faz, through: :bar
end

我希望能够致电foo1.merge!(foo2)

使用class.reflect_on_all_associations,我抓取了:has_many个反射列表以执行合并(常规列和has_one已被处理)

has_manys = self.class.reflect_on_all_associations(:has_many).select do |has_many|
  exclude.exclude?(has_many.name) && !has_many.options[:through]
end

has_manys.each do |has_many|
   local = public_send(has_many.name)
   remote = other.public_send(has_many.name) - local
   remote.reject! { |r| r.try(:skip_merge_if, self, other) } # callback hook for some custom logic

   local << remote # ActiveRecord::RecordNotUnique
end

我被困在这里,寻求有关如何解决ActiveRecord::RecordNotUnique的建议。在这种情况下,由于我是从Foo的那一边工作,所以我不知道定义了直通关系(从foo-> bar-> faz),所以我不确定如何进行dedup。

我可以为特定的直通关系添加一个选项,但是在产品中,我需要进行20-30个关联。如果有更清洁的溶液,将不胜感激。

0 个答案:

没有答案