before_create - 销毁多条记录
好的,我试图在 before_create 中销毁多条记录:
class InventoryItem < ActiveRecord::Base
belongs_to :user
belongs_to :item
before_create :replace_owned_items
protected
def replace_owned_items
user = self.user
item = self.item
owned_items = user.retrieve_owned_items(item)
unless owned_items.blank?
owned_items.each do |o|
o.destroy
end
end
end
end
我的问题是只有一条记录最终被销毁。
另一个是如果我使用 destroy! (如果它不破坏,我希望引发异常),然后我完全得到一个错误。
如何在 before_create 中销毁多条记录?
Ok, I am trying to destroy multiple records in a before_create:
class InventoryItem < ActiveRecord::Base
belongs_to :user
belongs_to :item
before_create :replace_owned_items
protected
def replace_owned_items
user = self.user
item = self.item
owned_items = user.retrieve_owned_items(item)
unless owned_items.blank?
owned_items.each do |o|
o.destroy
end
end
end
end
My issue is that only one record ends up being destroyed.
The other is that if I use destroy! (I want an exception to be raised if it doesn't destroy), then I get an error altogether.
How do you accomplish destroying multiple records in a before_create?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你尝试一下这个呢?
破坏!不是命令。如果由于某种原因它没有被破坏,你就会得到一个错误。此操作不需要 bang(!)。
What about if you try this?
destroy! isn't a command. If it doesn't destroy for whatever reason, you will get an error. The bang(!) would not be necessary for this operation.
据我所知,您无法使用 :id 参数将 ids 数组发送到 destroy_all 。我会像这样调整这个:
但我认为你之前的应该可以正常工作(下面的示例假设retrieve_owned_items返回一个空白数组,如果没有的话:
You can't send the array of ids to destroy_all with an :id parameter as far as I know. I'd tweak that one like this:
but I think what you had before should work fine (my example below assumes retrieve_owned_items returns a blank array if there are none: