ActiveRecord - has_many: via ,: dependent =>: destroy sql is invalid

I am trying to "match the cache" the number of posts in each tag. The callback after saving works, but not after the destruction. It seems that sql destruction is wrong.

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

Test does not work

# @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}
+5
source share
3 answers

I had the same problem, the fix for me was to add a primary key column to the connection table (PostTag in your case).

It seems that the rails need a primary key for the option :dependent => :destroy.

+1
source

increment/decment count + save. , , , .

class PostTag < ActiveRecord::Base

  belongs_to :post
  belongs_to :tag

  after_create  :increment_tag_posts_counter
  after_destroy :decrement_tag_posts_counter

  private

  def increment_tag_posts_counter
    Tag.increment_counter :posts_count, post_id
  end

  def decrement_tag_posts_counter
    Tag.decrement_counter :posts_count, post_id
  end
end
0

Maybe because in the models you used

#post.rb
has_many :post_tags, :dependent => :destroy
#tag.rb
has_many :post_tags, :dependent => :destroy

instead

#post.rb
has_many :posts_tags, :dependent => :destroy
#tag.rb
has_many :posts_tags, :dependent => :destroy

?

0
source

All Articles