clowne icon indicating copy to clipboard operation
clowne copied to clipboard

Nested include_association duplication

Open varg90 opened this issue 2 years ago • 7 comments

Hello. In my app I have a models scheme similar to the next:

class Table
  has_many :rows
  has_many :columns
end

class Row
  belongs_to :table
  has_many :cells
end

class Column
  belongs_to :table
  has_many :cells
end

class Cell
  belongs_to :row
  belongs_to :column
end

and cloners:

class TableCloner < Clowne::Cloner
  adapter :active_record

  include_association :rows
  include_association :columns

  finalize do |source, record, **params|
    record.title = "Copy of #{source.title}"
  end
end

class RowCloner < Clowne::Cloner
  adapter :active_record

  include_association :cells
end

class ColumnCloner < Clowne::Cloner
  adapter :active_record

  include_association :cells
end

class CellCloner < Clowne::Cloner
  adapter :active_record
end

Unfortunately, when I try to clone the Table

operation = TableCloner.call(original_table)
operation.persist!

I get correct table, rows and columns, but cells are cloned twice and it seems that both are wrong: one cells set has wrong row_id from the original_table rows and correct column_id from the cloned_table columns and the second cells set has correct row_id from the cloned_table rows but wrong column_id from the original_table columns

It seems that it doesn't understand how to sync all these record cloners (two dimensional table) and does clone rows and columns associations independent from each other. Could you help me to understand how to clone such a scheme properly?

Thank you

varg90 avatar Apr 11 '22 15:04 varg90

clowne 1.4.0 ruby 3.0.2 rails 6.1.4

varg90 avatar Apr 11 '22 15:04 varg90

Didn't find anything better than just to re-fill cell.column_id in the CellCloner:

after_persist do |source, clone, mapper:, **|
  if source.column_id
    column = mapper.clone_of(source.column)
    clone.update(column_id: column.id)
  end
end

Which does not sound as a best practice and produces a lot of needless SQL queries.

varg90 avatar Apr 14 '22 13:04 varg90