Rails has_many relationship is weird

I am not sure if anyone had noticed this before because I could not find a single topic on this issue. But provided that you have a product model and a Cart model that installs has_many :products. and a product model belongs_to :cart, a strange thing happens when you install an instance of a product cart_id(which is a foreign key that refers to the identifier of the associated cart) to nil. Three things are possible:

  • If you have already downloaded the linked basket before installing the linked product cart_idin nil, when you destroy an instance of that basket using the instance method destroy(), the corresponding product will also be destroyed .

  • If you download the linked basket AFTER installing the appropriate product cart_idin nil, when you destroy it using the instance method destroy, the related product will NOT be destroyed .

  • If you cancel the cart_idrelated product and call the CLASS METHOD destroyin the Cart ( Cart.destroy(cart_id)), the related product will NOT be destroyed

I am sure that this is related to the implementation has_many. It is likely that the state of the relationship becomes rigidly attached to the model instance when you retrieve it. See the code below:

Here is a sample code that I used to test above (if you already have the two above model tables)

Cart.create   # Assume this one has an id of 1
Product.create(cart_id: 1)
cart=Cart.find(1) # Retrieve the cart before
Product.find(1).update_attribute!(cart_id: nil)
cart.destroy
Product.find_by_id(1)   # nil; the associated product was destroyed

Cart.create # Assume this one has an id of 1
Product.create(cart_id: 1)
Product.find(1).update_attribute!(cart_id: nil)
cart=Cart.find(1) # Retrieve the cart AFTER
cart.destroy
Product.find_by_id(1) # [<Product id:1 cart_id:1 ....>], the assoc product WAS NOT destroyed

Cart.create # Assume this one has an id of 1
Product.create(cart_id: 1)
Product.find(1).update_attribute!(cart_id: nil)
Cart.destroy(1)
Product.find_by_id(1) # [<Product id:1 cart_id:1 ....>], the assoc product WAS NOT destroyed
+3
source share
1 answer

, " " , . -, , , , , ( , ).

, .

Ale, który pokazałeś jest warty odnotowania sam pewnie bym wpadł w jego pułapkę.

0

All Articles