makandra / active_type

Make any Ruby object quack like ActiveRecord
MIT License
1.09k stars 74 forks source link

nests_one association builds with blank attributes instead of passed in attributes. #119

Closed chriscz closed 4 years ago

chriscz commented 4 years ago

I've written an extension to ActiveType that invokes validation immediately after initialization, short and sweet, but there's a problem when assigning to a nested attribute.

module ActiveTypeValidateOnInitialize
  extend ActiveSupport::Concern

  included do
    after_initialize { validate! }
  end
end

class Keyboard < ActiveType::Object
   include ActiveTypeValidateOnInitialize

   attribute :layout, :string

   validates_presence_of :layout
end

class Computer < ActiveType::Object
  nests_one :keyboard, scope: proc { Keyboard }
end

c = Computer.new
# Below raises a ValidationError because of the code in `nests_one_association.rb` that calls build a Keyboard instance with blank attributes.
c.keyboard_attributes =  {layout: "US"}

The problem lies in the code below https://github.com/makandra/active_type/blob/8cd3c4678bf42b497c9832fbf9b1da4af992204c/lib/active_type/nested_attributes/nests_one_association.rb#L32-L35 which builds the nested object with a blank hash before assigning the attributes to the object.

The fix is simple

if assigned_child
  assigned_child.attributes = attributes
else
  add_child(parent, build_child(parent, attributes))
end

The code for the nests_many association looks correct https://github.com/makandra/active_type/blob/8cd3c4678bf42b497c9832fbf9b1da4af992204c/lib/active_type/nested_attributes/nests_many_association.rb#L40-L42

Would it be possible to make a release as well after fixing this? :)

kratob commented 4 years ago

Sorry for the late response. If you turn this into a merge request, we would have no issues merging this.