clowne-rb / clowne

A flexible gem for cloning models
https://clowne.evilmartians.io
MIT License
316 stars 18 forks source link

Feat: Access mapper in after_clone #48

Closed tuanmai closed 2 years ago

tuanmai commented 4 years ago

Summary

From this docs, I see that we can use after_commit to fix broken associations. But there is another use case that needs to fix the associations before save, and it's better to in after_clone phrase.

Example

class Organisation < ActiveRecord::Base
  # create_table :organisations do |t|
  # end

  has_many :leave_requests
  has_many :leave_categories
end

class LeaveCategory < ActiveRecord::Base
  # create_table :leave_categories do |t|
  #   t.integer :organisation_id
  # end

  has_many :leave_requests
end

class LeaveRequest < ActiveRecord::Base
  # create_table :leave_requests do |t|
  #   t.integer :organisation_id
  #   t.integer :leave_category_id
  # end

  belongs_to :organisation
  belongs_to :leave_category
end

When cloning org, to map leave requests to cloned leave categories, we need to do it in after_clone step by using mapper.

ssnickolay commented 4 years ago

Hi @tuanmai! I'm not quite sure what the problem you try to resolve with mapper inside after_clone instead doing it inside after_persist. You want to use mapper BEFORE any saving to DB to fix some associations, right? If so, could you add small test, please? There is good place for it . Btw, you can extend existing models if they are not enough for your case.

tuanmai commented 4 years ago

@ssnickolay sure, I will add the test for it 👍

Subtletree commented 4 years ago

This is a great idea @tuanmai. Anything I can help with?