我不确定以前是否有人注意到这一点,因为我在这个问题上找不到任何话题。但假设您有产品型号和购物车型号has_many :products
。并且产品型号设置为belongs_to :cart
,当您将产品实例的cart_id
(这是引用相关购物车ID的外键)设置为nil
时,会发生奇怪的事情。三件事情可能发生:Rails has_many关系很奇怪
如果你已经获取的相关车前设置了相关产品的
cart_id
到nil
,当你使用它的实例方法destroy()
,相关产品被破坏以及摧毁车实例。如果您检索相关的车后设置相关产品的
cart_id
到nil
,当你使用它的实例方法destroy
,相关产品没有得到破坏摧毁它。如果你废了相关产品的
cart_id
,并呼吁车(Cart.destroy(cart_id)
)类方法destroy
,相关产品没有得到破坏
我敢肯定,这有某事与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
这就是我在帖子中所说的。我希望能够更多地了解幕后的情况,但我不认为自己已经足够阅读源代码了。 – 2012-04-28 19:21:04
对不起,我有点嗡嗡声。周六,你知道;) – Eraden 2012-04-28 19:37:40
这可能是由于类似于控制缓存:不知何故,当你检索购物车时,相关产品对象被检索和缓存(或以某种方式“记录”),并在下一次通过调用Cart#产品,只需从缓存中检索它们 – 2012-04-30 03:36:20