Tôi đang cố gắng "truy cập bộ nhớ cache" số lượng bài đăng trong mỗi thẻ. Sau khi lưu gọi lại là làm việc nhưng sau khi tiêu diệt là không. Hình như phá hủy sql là không chính xác.ActiveRecord - has_many: thông qua,: depend =>: destroy sql không đúng
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
Thử nghiệm thất bại
# @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
Các sql đúng nên
DELETE FROM `posts_tags` WHERE `posts_tags`.`post_id` = {the post id}
Hãy thử sử dụng set_table_name thay vì table_name =? Tôi nghĩ rằng phương thức set_table_name thay đổi một vài thứ khác. –
@joe Pym Điều đó không hiệu quả. Ngoài ra, set_table_name hiện không còn được dùng nữa. -> CẢNH BÁO KHÔNG DÙNG: Gọi set_table_name không được chấp nhận. Thay vào đó, hãy sử dụng 'self.table_name = 'the_name''. – Marcelo
Tôi nhận được một lỗi rất giống nhau trong tình huống của tôi. Tôi cũng muốn một câu trả lời. – user1149547