Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord - has_many :through, :dependent => :destroy sql is not correct

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}
like image 799
Marcelo Avatar asked Oct 23 '22 04:10

Marcelo


1 Answers

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.

like image 104
Paludis Avatar answered Nov 08 '22 08:11

Paludis