A better way to delete all associated records in a join tabl

Hiya,

I have a has_many :through relationship

Sites
Channels
Site_Channels

When creating a record, i can simply do:

channels = Channel.find params[:channels]
@site.channels << channels

When I update, I can’t take that same approach because << appends, so
I’m
currently doing:

@site.site_channels.destroy_all

I know this is ugly (to some extent), so does anyone else have a better
way
I could be doing this?

Thanks.

On Jan 2, 2007, at 07:20 , kris wrote:

I have a has_many :through relationship
[SNIP]
When I update, I can’t take that same approach because << appends,
so I’m currently doing:

@site.site_channels.destroy_all

I know this is ugly (to some extent), so does anyone else have a
better way I could be doing this?

http://www.railsapi.org/has_many states that has_many collections get
a clear method. I have a feeling that might be what you’re looking for:

collection.clear - removes every object from the collection. This
destroys the associated objects if they are :dependent, deletes them
directly from the database if they are :dependent => :delete_all, and
sets their foreign keys to NULL otherwise.

It should work with has_many :through as well, I imagine.


Jakob S. - http://mentalized.net

On Jan 2, 2007, at 07:20 , kris wrote:


Jakob S. - http://mentalized.net