amoeba-rb/amoeba

Child association might be duplicated before the parent?

Opened this issue · 3 comments

First off, in what order are the model and associations duplicated? I couldn't tell from the documentation.

Secondly, I'm trying to duplicate a Site record, which in turn is duplicating the association. This is fine. The issue is that I'm hitting a validation on the child Placement model before the duplicated Site is created.

Simplified code...

class Placement < ActiveRecord::Base
  belongs_to :site, inverse_of: :placements
  validate :site_must_have_stuff, if: proc { |record| record.some_condition? }

  def site_must_have_stuff
    if site.url.blank?
      errors.add(:url, "must be present")
      false
    else
      true
    end
  end
end

class Site < ActiveRecord::Base
  has_many :placements, inverse_of: :site
end

site = Site.new(attributes)
site.amoeba_dup  #=> (Placement invalid error)

Am I doing something wrong? Is the expected behavior to create the duplicated associations before the object you call amoeba_dup on? And if all of this is true, is there a way to coerce the duplication order?

qnsi commented

Hey did you figure out something in this matter?
I have similar problem, I have two models with has_many relationship. (X and Y for example)
Sometimes X may have multiple Y, but sometimes I validate that it has only one Y.

Now when I try to clone X with just one Y (and validations for this), Y is copied first, and it can't be saved (because now X has two Ys).

Would be cool to hear about possible workarounds.

I can't recall the exact workaround, but if I remember correctly, I played around with the various callbacks such as before_save, before_commit, after_save, after_commit etc. I believe some combination of this between the two models made it work. Good luck!

Is the expected behavior to create the duplicated associations before the object you call amoeba_dup on? And if all of this is true, is there a way to coerce the duplication order?

I've hit upon these two questions, too.

I have an association whose duplicated object needs to access a "customized" value on its duplicated parent, however this doesn't seem to be possible -- by default. Is there any way to invert the order of the duplications? Is there a known workaround for doing this sort of thing?

UPDATE:
I was unable to find a solution using amoeba, but I solved my problem by adding columns to the parent (duplicate and duplicate_source_id) and setting those using the customize macro. I then used those columns in an after_create callback on the child model in order to access the attributes on the source model.