Answer the question
In order to leave comments, you need to log in
How to copy the object correctly in this case?
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
}
]
}
praent_id
this is the ID of the same model that has it nil
. dup
new_obj = obj.dup
new_obj.save!
obj.models.each do |m|
new_obj.models << m.dup
end
parent_id
it remains the same.[
{
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
}
]
parent_id
for models?
Answer the question
In order to leave comments, you need to log in
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question