Mar*_*elo 5 activerecord many-to-many ruby-on-rails
我试图"反缓存"每个标签中的帖子数量.后保存回调正在工作,但后毁灭不是.看起来像破坏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
Run Code Online (Sandbox Code Playgroud)
测试失败
# @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
Run Code Online (Sandbox Code Playgroud)
应该是正确的sql
DELETE FROM `posts_tags` WHERE `posts_tags`.`post_id` = {the post id}
Run Code Online (Sandbox Code Playgroud)
我建议单独的递增/递减函数,而不是使用计数+保存。这应该正常工作,表现良好,不会触发标签的副作用,并且不会在竞争条件下弄乱你的计数。
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
818 次 |
| 最近记录: |