views:

33

answers:

2

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?

+2  A: 

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.

Geoff Lanotte
A: 

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
Sean Johnson