D
D
Demigodd2020-04-03 08:26:55
ruby
Demigodd, 2020-04-03 08:26:55

How to copy the object correctly in this case?

Type of object to copy
obj = {
id: 1
models: [
    {
      id: 1,
      parent_id: nil
    },
    {
      id: 2,
      parent_id: 1
    },
    {
      id: 3,
      parent_id: 1
    },
    {
      id: 4,
      parent_id: nil
    },
    {
      id: 5,
      parent_id: 4
    },
    {
      id: 6,
      parent_id: 4
    }
  ]
}


There is an object of this type.
praent_idthis is the ID of the same model that has it nil.
When copying it using the methoddup
new_obj = obj.dup
new_obj.save!

obj.models.each do |m|
  new_obj.models << m.dup
end


After copying, parent_idit remains the same.

Correct result
Дата перед копированием.
[
 {
   id: 123,
   parent_id: nil
 },
 {
   id: 456,
   parent_id: 123
 }
]


и после копирования
[
 {
   id: 457,
   parent_id: nil
 },
 {
   id: 458,
   parent_id: 123
 }
]


Правильный результат, должен быть.
[
 {
   id: 457,
   parent_id: nil
 },
 {
   id: 458,
   parent_id: 457
 }
]


How in this case it is correct to distribute parent_idfor models?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Mirilaczvili, 2020-04-03
@Demigodd

If I understand the logic of copying parent_id correctly:

new_obj = {id: new_id, models: []}
prev_model = nil
obj[:models].each do |m|
  new_model = m.dup
  new_model[:parent_id] = prev_model[:id] unless prev_model.nil?
  new_obj[:models] << new_model
  prev_model = new_model
end

 result
{:id=>2,
:models=>
[{:id=>1, :parent_id=>nil},
{:id=>2, :parent_id=>1},
{:id=>3, :parent_id=>2},
{:id=>4, :parent_id=>3},
{:id=>5, :parent_id=>4},
{:id=>6, :parent_id=>5}]}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question