Why does #destroy() DELETE FROM one at a time?

I have a pair of models with a fairly standard :has_many relation. The
only twist is that the has_many table is a namespaced STI table:

module MeteredService
class Base < ActiveRecord::Base
has_many :service_bills, :foreign_key => :metered_service_id,
:dependent => :destroy

end
end

class ServiceBill < ActiveRecord::Base
belongs_to :metered_service, :class_name => “MeteredService::Base”,
:foreign_key => “metered_service_id”

end

When I do

my_metered_service.destroy

Rails generates individual DELETE FROM commands (and there are a lot of
them)

DELETE FROM “service_bills” WHERE “service_bills”.“id” = $1 [[“id”,
633398]]
DELETE FROM “service_bills” WHERE “service_bills”.“id” = $1 [[“id”,
633399]]

Question 1: Is this the expected behavior? I would think Rails would be
smart enough to do the deletions in a single statement along the lines
of:

DELETE FROM “service_bills” WHERE metered_service.id =
my_metered_service.id

Question 2: If this is NOT the expected behavior, have I set up my STI
relations incorrectly?

Sometimes I intentionally introduce small typos to see if you’re paying
attention! :slight_smile: The suggested SQL should have read:

DELETE FROM “service_bills” WHERE metered_service_id =
my_metered_service.id

On Feb 16, 2012, at 10:40 AM, Fearless F. wrote:

Rails generates individual DELETE FROM commands (and there are a lot of
smart enough to do the deletions in a single statement along the lines
of:

It is expected. You’ve set :dependent => :destroy. That tells Rails
that you want to instantiate each of the related objects and call
destroy on it – in order that each of those objects destroy callbacks
also get called.

DELETE FROM “service_bills” WHERE metered_service.id =
my_metered_service.id

Question 2: If this is NOT the expected behavior, have I set up my STI
relations incorrectly?

If you don’t need to pick up any of those callbacks you can set
:dependent => :delete_all

See the docs for :has_many for more info…

-philip