Has_and_belongs_to_many with fk constraints?


#1

Hi folks,
I’m wondering if it’s possible to use foreign key constraints on the
join
tables of a has_and_belongs_to_many relation. Specifically, I get this
error when I try and delete a model I’m using, named saved_search, which
is
many-to-many with neighborhoods. Any ideas? Thanks for any help. :slight_smile:

-Eric

Code:
@saved_search.destroy

Error:
Mupdate or delete on “saved_searches” violates foreign key constraint
“neighborhoods_saved_searches_saved_searches_saved_search_id_fk” on
“neighborhoods_saved_searches” DKey (id)=(1) is still referenced from
table
“neighborhoods_saved_searches”. Fri_triggers.c L3302
Rri_ReportViolation:
DELETE FROM saved_searches WHERE id = 1

Models

class SavedSearch < ActiveRecord::Base
has_and_belongs_to_many :neighborhoods
end

class Neighborhoods < ActiveRecord::Base
has_and_belongs_to_many :saved_searches
end

Join table:
neighborhoods_saved_searches

id INTEGER NOT NULL PRIMARY KEY
saved_search_id INTEGER NOT NULL foreign key table:
saved_searches field: id
neighborhood_id INTEGER NOT NULL foreign key table:
neighborhoods field: id

The other tables, saved_search, and listings, are normal and have
integer id
fields as required.