lundi 23 octobre 2017

create_relation vs Relation.create - Minitest failing on first option

I'm having an odd issue and I'm not sure what is going on, so looking for some clarity. I have a model, let's call it Parent, and Parent has a child relationship called Child. Currently, my code is setup like this:

@parent = Parent.new(@parent_attributes)
if (@parent.save)
   @parent.create_child
end

This code resides in a service, and works just fine and dandy when running the app normally through the controller.

But when I try to test the service directly, this code fails, with null exception that the parent_id isn't set. The parent has_one :child, inverse_of: :parent and the child belongs_to :parent, inverse_of :child

The thing that makes no sense to me, is that if I change the above code to:

if (@parent.save)
   @parent.child = Child.create
end

the test works just fine. Can anyone explain to me why this would be?

Aucun commentaire:

Enregistrer un commentaire