If I have a simple tagging system, with three models: posts, tags, and
posts_tags; and I delete a tag, then naturally I would want to delete
any associations in posts_tags that include that tag, right?
But I don’t want to create a model for my posts_tags table; something
tells me Rails has a way of removing records from join tables
automatically. But I don’t know where I would start from for that.
Anybody care to set me on the right path?
If I have a simple tagging system, with three models: posts, tags, and
posts_tags; and I delete a tag, then naturally I would want to delete
any associations in posts_tags that include that tag, right?
But I don’t want to create a model for my posts_tags table; something
tells me Rails has a way of removing records from join tables
automatically. But I don’t know where I would start from for that.
Anybody care to set me on the right path?
Thanks!
has_many :model :dependent => :destroy
Use the dependent option which will delete the association
:delete_sql - overwrite the default generated SQL used to remove links
between the associated classes with a manual one
So that means that ActiveRecord has ‘default generated SQL used to
remove links between the associated classes’ out of the box already,
right? So maybe I don’t have to do anything!
"
class Tag < ActiveRecord::Base
has_and_belongs_to_many :posts, :dependent => :delete_all
end
"
?
I see the has_and_belongs_to_many cannot use the :dependent key, only
the has_many can use it
You can use then the :delete_sql key
Example from the documentation:
has_and_belongs_to_many :active_projects, :join_table =>
‘developers_projects’, :delete_sql =>
‘DELETE FROM developers_projects WHERE active=1 AND developer_id =
#{id} AND project_id = #{record.id}’