before_create - 销毁多条记录

发布于 2024-09-09 01:07:27 字数 541 浏览 5 评论 0原文

好的,我试图在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

帅冕 2024-09-16 01:07:27

如果你尝试一下这个呢?

def replace_owned_items
  owned_items = user.retrieve_owned_items(item).map(&:id)
  Item.destroy_all(:id => owned_items) unless owned_items.blank?
end

破坏!不是命令。如果由于某种原因它没有被破坏,你就会得到一个错误。此操作不需要 bang(!)。

What about if you try this?

def replace_owned_items
  owned_items = user.retrieve_owned_items(item).map(&:id)
  Item.destroy_all(:id => owned_items) unless owned_items.blank?
end

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.

帝王念 2024-09-16 01:07:27

据我所知,您无法使用 :id 参数将 ids 数组发送到 destroy_all 。我会像这样调整这个:

def replace_owned_items
  owned_items = user.retrieve_owned_items(item).map(&:id)
  for item in owned_items do
    Item.destroy(item.to_i)
  end
end

但我认为你之前的应该可以正常工作(下面的示例假设retrieve_owned_items返回一个空白数组,如果没有的话:

def replace_owned_items
  owned_items = user.retrieve_owned_items(item)
  for item in owned_items
    item.destroy
  end
end

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:

def replace_owned_items
  owned_items = user.retrieve_owned_items(item).map(&:id)
  for item in owned_items do
    Item.destroy(item.to_i)
  end
end

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:

def replace_owned_items
  owned_items = user.retrieve_owned_items(item)
  for item in owned_items
    item.destroy
  end
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文