Deep Nesting Help

I’m not sure I understand what’s the problem, where exactly do you have doubts?

I’d suggest you first refactor that super ugly nested loops and ifs:

  • remove the unnecesarry if’s

DdCategory.all.each do |category|

If the Category is active, build it

if category.is_active?

can’t you handle that is_active? with a scope?

  • the blocks for category.dd_items and subcategory.dd_items looks almost the same, I think you can reuse some code there

  • move complex logic to other methods to clean that up, like:

item.dd_subitems.each do |subitem|

newitem.dd_detail_subitems.create!(dd_detail_item_id:, title: subitem.title, has_check: subitem.has_check, has_value: subitem.has_value, has_note: subitem.has_note, item_check: subitem.item_check, item_value: subitem.item_value, item_note: subitem.item_note)


could be a method on newitem like “add_subitem_from(subitem)” that does that create but you’ll have less clutter to simplify your logic to understand it better

But what’s the actual problem? you say you have some problem but you just pasted code with no indication on where to look. Do you have a render error? do you have the view rendering ok but when you submit it it does not do what you want? if it does not do what you want, what’s the excepted vs the actual behaviour?