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

Excluding a 'has_many' relationship fails #119

Closed damiong28 closed 4 years ago

damiong28 commented 4 years ago

When you want to exclude a 'has_many' from the clone, it fails with the following error message:

1) Error: TestDeepCloneable#test_single_deep_clone_of_has_many_relationship: ActiveModel::MissingAttributeError: can't write unknown attribute mateys /Users/damion/.rvm/gems/ruby-2.4.1/gems/activemodel-5.2.0/lib/active_model/attribute.rb:207:in with_value_from_database' /Users/damion/.rvm/gems/ruby-2.4.1/gems/activemodel-5.2.0/lib/active_model/attribute_set.rb:57:inwrite_from_user' /Users/damion/.rvm/gems/ruby-2.4.1/gems/activerecord-5.2.0/lib/active_record/attribute_methods/write.rb:51:in _write_attribute' /Users/damion/.rvm/gems/ruby-2.4.1/gems/activerecord-5.2.0/lib/active_record/attribute_methods/write.rb:45:inwrite_attribute' /Users/damion/.rvm/gems/ruby-2.4.1/gems/activerecord-5.2.0/lib/active_record/attribute_methods.rb:410:in []=' /Users/damion/deep_cloneable/lib/deep_cloneable/deep_clone.rb:183:indup_default_attribute_value_to' /Users/damion/deep_cloneable/lib/deep_cloneable/deep_clone.rb:24:in block in deep_clone' /Users/damion/deep_cloneable/lib/deep_cloneable/deep_clone.rb:23:ineach' /Users/damion/deep_cloneable/lib/deep_cloneable/deep_clone.rb:23:in deep_clone' /Users/damion/deep_cloneable/test/test_deep_cloneable.rb:34:intest_single_deep_clone_of_has_many_relationship'

You can recreate this by adding this test to your suite:

  def test_single_deep_clone_excluding_has_many_relationship
    deep_clone = @jack.deep_clone(:except => :mateys)
    assert deep_clone.new_record?
    assert deep_clone.save
    assert_equal @jack.name, @jack.deep_clone.name
    assert_nil deep_clone.name
    assert_equal @jack.nick_name, deep_clone.nick_name
  end
moiristo commented 4 years ago

except is not meant to exclude associations, it is meant for excluding attributes. If you don't want an association to be included, you need to omit it from the include option. By default, no associations are included at all. @jack.deep_clone is exactly the same as calling @jack.dup.