我正在尝试“计数器缓存”每个标签中的帖子数量。保存后回调有效,但销毁后无效。看起来 destroy sql 不正确。
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
测试失败
# @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
正确的sql应该是
DELETE FROM `posts_tags` WHERE `posts_tags`.`post_id` = {the post id}
最佳答案
我遇到了完全相同的问题,对我来说,解决方法是在连接表中添加一个主键列(在您的情况下为 PostTag)。
似乎 rails 需要 :dependent => :destroy
的主键工作的选择。
关于ruby-on-rails - ActiveRecord - has_many :through, :dependent => :destroy sql 不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9911078/