moiristo / deep_cloneable

This gem gives every ActiveRecord::Base object the possibility to do a deep clone that includes user specified associations.
MIT License
786 stars 88 forks source link

Conditional nested includes #130

Closed lHydra closed 3 years ago

lHydra commented 3 years ago

If I add a condition to one of the top nodes, then all nested associations are not cloned. Is this a bug?

For example, this is array for include associations:

[
  owned_company: [
      ...,
      housing_estates: [
          ...,
          houses: [
              ...,
              apartments: [
                  ...
              ],
          ], 
          if: ->(housing_estate) { housing_estate.id == 1 }
      ]
  ]
]

So my replica object will have copy housing_estate with ID 1, but without houses & apartments. If I remove condition row, then I will get correct result with associations.

moiristo commented 3 years ago

Possibly. Maybe something is wrong here in that case. But I first need to be able to reproduce the bug by creating a failing test. I'll look into it shortly. PRs are welcome of course :)

moiristo commented 3 years ago

Hi @lHydra,

I think I found the issue. In the code, I expect the conditional to be a hash on its own. However, in your case the nested includes are also in there. There are two solutions. One of them is in master now and changes the way the conditionals are parsed. The other one is to rewrite the include:

# Don't do this
owned_company: [ housing_estates: [:apartments], if: ->(housing_estate) { housing_estate.id == 1 } ]

# Do this instead
owned_company: [{ housing_estates: [:apartments] }, if: ->(housing_estate) { housing_estate.id == 1 } ]