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

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.

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?

railsapi.org - railsapi Resources and Information. 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.

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.

>