moiristo / deep_cloneable

This gem gives every ActiveRecord::Base object the possibility to do a deep clone that includes user specified associations.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Excluding a 'has_many' relationship fails

damiong28 opened this issue · comments

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:in write_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:in write_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:in dup_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:in each'
    /Users/damion/deep_cloneable/lib/deep_cloneable/deep_clone.rb:23:in deep_clone' /Users/damion/deep_cloneable/test/test_deep_cloneable.rb:34:in test_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

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.