Monday, February 15, 2010

How to delete a many-to-many association with Rails

One solution is to create a new model for the association. It should be the case
if you add attributes to the association (because push_with_attributes is now deprecated).
You can then simply find the association given the ids of your linked object and call destroy.

However, when you don't have any attribute in your liaison, the has_and_belongs_to_many
is nicer to work with. (you don't need a rails model for the liaison.)
Here is a link to the methods has_and_belongs_to_many adds where we can read :


"collection.delete(object, …) - removes one or more objects from the
collection by removing their associations from the join table.
This does not destroy the objects."

Let's assume we dispose of 2 models 'Post' and 'Category' with a N-N association :

class Post < ActiveRecord::Base
has_and_belongs_to_many :categories
end

class Category < ActiveRecord::Base
has_and_belongs_to_many :posts
end

To delete an association (remove a post from a category) you can use this method :

  def remove_post_from_category
post = Post.find(params[:post][:id])
category = post.categories.find(params[:category][:id])

if category
post.categories.delete(category)
end

end

This function will destroy the association but won't destroy the category.

You can also removes all the categories from the posts by using :


collection.clear - removes every object from the collection.
This does not destroy the objects.
In our case its

post.categories.clear

No comments:

Post a Comment