この問題に関するトピックが見つからなかったため、以前に誰かがこれに気付いたかどうかはわかりません。ただし、を設定するProductモデルとCartモデルがあると仮定しますhas_many :products
。製品モデルが設定されている場合、製品インスタンス(関連付けられたカートのIDを参照する外部キー)をにbelongs_to :cart
設定すると、奇妙なことが起こります。次の3つのことが起こります。cart_id
nil
cart_id
関連商品をに設定する前に関連カートを既に取得しているnil
場合、インスタンスメソッドを使用してそのカートインスタンスを破棄するとdestroy()
、関連商品も破棄されます。cart_id
関連商品をに設定した後で関連カートを取得する場合nil
、インスタンスメソッドを使用してカートを破棄するとdestroy
、関連商品は破棄されません。関連商品のを無効にしてカート
cart_id
のクラスメソッドを呼び出した場合( )、関連商品は破棄されませんdestroy
Cart.destroy(cart_id)
これは、の実装と関係があると確信していますhas_many
。おそらく、関係の状態は、モデルインスタンスを取得するときに、モデルインスタンスに組み込まれます。以下のコードを参照してください。
上記をテストするために使用したサンプルコードは次のとおりです(上記の2つのモデルテーブルがすでにあると仮定します)
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