moiristo / deep_cloneable

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

Nested has many associations #84

Closed jokklan closed 6 years ago

jokklan commented 7 years ago

When using deeply nested has many associations in include with conditions in include, will the conditional only be called for the first record. This PR is a fix to that bug.

Example:

class User < ActiveRecord::Base
  has_many :orders
end

class Order < ActiveRecord::Base
  belongs_to :user
  has_many :products
end

class Product < ActiveRecord::Base
  belongs_to :order
end

# Create a user with two orders, each with two products
@user = User.create :name => 'Jack'
@product1 = Product.create  :name => 'Paper'
@product2 = Product.create  :name => 'Ink'
@order1 = Order.create
@order2 = Order.create
@order1.products << [@product1, @product2]
@order2.products << [@product1, @product2]
@user.orders << [@order1, @order2]

# We don't want to clone the "Ink" product
deep_clone = @user.deep_clone(:include => [orders: [products: [{ :unless => lambda {|product| product.name == 'Ink' }}]]])

# However the conditional only works for the first order, because after that is the conditional deleted from the hash
deep_clone.orders[0].products.size #=> 1
deep_clone.orders[1].products.size #=> 2
jokklan commented 6 years ago

@moiristo thanks for merging :+1: And thanks for this gem, it's very useful :)!

moiristo commented 6 years ago

Thank you for the PR! I'll make a patch release for it later today!