当销毁一条记录时,另一条记录也会被销毁
产品(例如 iPod Classic) :has_many => :列表,:依赖 => :destroy
Listings(例如“我的名字是 Joe,我有一台 iPod 待售) :属于=> :product
因此,如果我删除给定的产品,则指向它的所有列表都会被删除。这是有道理的,也是设计使然。
但是,我正在编写一个“合并”功能,您可以将两个产品合并为一个,然后合并它们的列表。所以,假设我的两个产品是“iPod Color”和“iPod Classic”,我想合并这两个产品。我想做的是说,“iPod Color,合并到 iPod Classic”,结果应该是:
- 所有 iPod Color 列表都重新指向 iPod Classic 产品 产品
- ID 更改后,列表将被保存
- 然后我删除了“iPod Color”产品
好吧,这应该一切正常,无需删除任何列表。然而,我有这个控制器,无论出于什么原因,当我销毁“iPod Color”产品时,即使在确认列表已移动到“iPod Classic”并保存到数据库后,之前指向的列表“iPod Color”也被毁了,我不明白为什么。就好像他们保留了与被破坏的产品的某种联系,因此开始破坏自己。
我错过了什么明显的痛苦的事情?
def merge
merging_from = Product.find(params[:id])
merging_to = Product.find_by_model(params[:merging_to])
unless merging_to.nil?
unless merging_from.nil?
unless merging_from == merging_to # you don't want to merge something with itself
merging_from.listings.each do |l|
l.product = merging_to
l.save
end
# through some debugging, I've confirmed that my missing Listings are disappearing as a result of the following destroy call
merging_from.destroy
end
end
end
Products (like an iPod Classic)
:has_many => :listings, :dependent => :destroy
Listings (like "My name is Joe, and I have an iPod for sale)
:belongs_to => :product
So, if I delete a given Product, all the listings that point to it get deleted. That makes sense, and is by design.
However, I am writing a "merge" function, where you merge two Products into one, and combine their Listings. So, let's say my two products are "iPod Color" and "iPod Classic", and I want to merge the two. What I want to do is say, "iPod Color, merge into iPod Classic", and result should be that:
- All the iPod Color Listings are re-pointed to the iPod Classic product
- After the product_id change, the Listing(s) are saved
- I then delete the "iPod Color" product
Well, that should all work fine, without deleting any Listings. However, I've got this controller, and for whatever reason when I destroy the "iPod Color" Product, even after confirming that the Listings have been moved to "iPod Classic" and saved to the database, the Listings that were previously pointed to "iPod Color" get destroyed as well, and I can't figure out why. It's as if they are retaining some kind of link to the destroyed product, and therefore begin destroyed themselves.
What painfully obvious thing am I missing?
def merge
merging_from = Product.find(params[:id])
merging_to = Product.find_by_model(params[:merging_to])
unless merging_to.nil?
unless merging_from.nil?
unless merging_from == merging_to # you don't want to merge something with itself
merging_from.listings.each do |l|
l.product = merging_to
l.save
end
# through some debugging, I've confirmed that my missing Listings are disappearing as a result of the following destroy call
merging_from.destroy
end
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我看到了同样的行为并重新加载解决了它。
I saw the same behaviour and reload solved it.