Forum: Ruby on Rails HABTM Dependency Question

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
78461b02f7a5d5e7eecf94dd2cfb858c?d=identicon&s=25 Jason Ketterman (Guest)
on 2005-12-30 05:12
(Received via mailing list)
I have a habtm relationship like the following:

Automobile <--> Options

What I want to do is when an option is deleted, make sure that there
are no Automobiles that still have that option. It seems simple
enough, but I am having a tough time with it. I believe Rails
automagically deletes the relationships when the automobile is
deleted, but not the other way around.

Any help would be appreciated!

Thanks,
	Jason
A2c85dc5ee81b12e3cc0a6522e8d079d?d=identicon&s=25 Chris Hall (Guest)
on 2005-12-30 14:43
(Received via mailing list)
auto1 = Automobile.create(...)
auto2 = Automobile.create(...)
cdplayer = Option.create(...)

# add the cdplayer to both autos
auto1.options << cdplayer
auto2.options << cdplayer

# show options
auto1.options
auto2.options

# doing this will delete the cdplayer option and also remove any
cdplayer
relationships
# since cdplayer no longer exists in the database
cdplayer.destroy

# doing this will delete the auto1 automobile and also remove any auto1
relationships
# since auto1 no longer exists in the database
auto1.destroy
This topic is locked and can not be replied to.