2012-04-28 108 views
3

我不确定以前是否有人注意到这一点,因为我在这个问题上找不到任何话题。但假设您有产品型号和购物车型号has_many :products。并且产品型号设置为belongs_to :cart,当您将产品实例的cart_id(这是引用相关购物车ID的外键)设置为nil时,会发生奇怪的事情。三件事情可能发生:Rails has_many关系很奇怪

  1. 如果你已经获取的相关车前设置了相关产品的cart_idnil,当你使用它的实例方法destroy(),相关产品被破坏以及摧毁车实例。

  2. 如果您检索相关的车后设置相关产品的cart_idnil,当你使用它的实例方法destroy,相关产品没有得到破坏摧毁它。

  3. 如果你废了相关产品的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 

回答

0

我怀疑“奇怪的行为”的原因是,通过下载数据库对象也得到它的依赖。显然,即使数据库依赖关系不存在,删除所有者的讨价还价删除了从属元素(以及那些已经不存在的元素)。

因此,重新下载条目不会破坏关联。

麦芽酒问题,którypokazałeśjest warty odnotowania i sam pewnie bymwpadłw jegopułapkę。

+0

这就是我在帖子中所说的。我希望能够更多地了解幕后的情况,但我不认为自己已经足够阅读源代码了。 – 2012-04-28 19:21:04

+0

对不起,我有点嗡嗡声。周六,你知道;) – Eraden 2012-04-28 19:37:40

+0

这可能是由于类似于控制缓存:不知何故,当你检索购物车时,相关产品对象被检索和缓存(或以某种方式“记录”),并在下一次通过调用Cart#产品,只需从缓存中检索它们 – 2012-04-30 03:36:20