How do change catalog before catalog is delted?

In my rails application,there are two models:post and catalog. One post has a catalog,and one catalog has many posts. When I delete a catalog,the posts belongs to the catalog will not be shown normal,for it's catalog is no existed.

Now I want to create(if the 'Defalut catalog' is not existed) a 'Defalut catalog' in catalogs table,and make the posts's catalog belongs to it,before I delete a catalog.

I just know there is 'before_destory' in ActiveRecord.But I don't know how to do it.

Thanks for any replies.

There are several ways to do this, before_destroy is a good option

just do (in model) before_destroy : move_to_default

def move_to_default   #...code that sets a posts to the default...   # something like this   @default_catalog << posts end

I see a slight disadvantage here (depending on your app this may be wrong) You'll have a default catalog araound all the time and have to handle it, avoid that it's shown in the wrong places, where only "normal" catalogs should show You could simple nullify the associations of the posts and handle all posts if a catalog_id of NULL as belonging to default catalog. This would save you an extra dummy record in the catalog table.

A minor advantage of this would be, that Rails could handle this by itself in catalog model: has_many :posts, :dependent => :nullify would be all you need and Post.find(:all, :conditions => {catalog_id => nil}) would give you the abandoned posts as easy as the default catalog

I would follow the second option as Thorsten says, having dummy records that do noting helps no one. For example, in our apps, when we want to recreate this sort of behaviour, we do it straight in the model. so for example, records that have no name always return the same string defined in a constant. or users that dont have an avatar nearly always return their grvatar url if they have one, else they return our default avatar...etc etc

j