I am trying to "counter cache" the number of posts in each tag. The after save callback is working but the after destroy is not. Looks like destroy sql is not correct.
class Post < ActiveRecord::Base
has_many :post_tags, :dependent => :destroy
has_many :tags, :through => :post_tags
end
class Tag < ActiveRecord::Base
has_many :post_tags, :dependent => :destroy
has_many :posts, :through => :post_tags
end
class PostTag < ActiveRecord::Base
self.table_name = :posts_tags
belongs_to :post
belongs_to :tag
after_save :update_tag_posts_count
after_destroy :update_tag_posts_count
def update_tag_posts_count
tag.posts_count = tag.posts.count
tag.save
end
end
The test fails
# @tag.posts_count == 10
Failure/Error: @tag.posts.first.destroy
ActiveRecord::StatementInvalid:
Mysql2::Error: Unknown column 'posts_tags.' in 'where clause': DELETE FROM `posts_tags` WHERE `posts_tags`.`` = NULL
The correct sql should be
DELETE FROM `posts_tags` WHERE `posts_tags`.`post_id` = {the post id}
I had the exact same issue, the fix for me was to add a primary key column to the join table (PostTag in your case).
It seems that rails needs a primary key for the :dependent => :destroy
option to work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With