无法删除我的评论对象的记录

时间:2015-08-06 08:22:38

标签: mysql ruby-on-rails ruby-on-rails-4 acts-as-commentable

假设我的Rails应用程序通过使用acts_as_commentable_with_threading gem而具有Recipe和Comment的关系,并且Recipe gem已配置paranoid2 gem。从旧系统迁移到新系统,我通过手动将记录插入Comment表创建了新记录,但错误地为每个配方创建了重复的注释。现在我想通过修改this SO question的解决方案来删除重复的记录。

# app/models/recipe.rb
class Recipe < ActiveRecord::Base
  acts_as_commentable
  paranoid

  # other configurations and methods

end


# app/models/comment.rb
class Comment < ActiveRecord::Base
  paranoid

  def self.dedupe_recipe_comments
    grouped = all.where(commentable_type: "Recipe").group_by{|model| [model.commentable_id,model.body,model.user_id,model.commentable_username] }
    grouped.values.each do |duplicates|
      first_one = duplicates.shift

      duplicates.each do |double| 
      puts "removing #{double.inspect} from table"
      double.destroy(force: true)
    end

  end

end

但是当我在Rails控制台中调用此函数时,此函数会返回错误,假设第一个重复记录的id为1480:

  

ActiveRecord :: RecordNotFound:无法找到带有'id'= 1480的评论   来自/Users/yoonwaiyan/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/activerecord-4.1.0/lib/active_record/relation/finder_methods.rb:320:in`lift_record_not_found_exception!'

但是当我尝试使用Comment.find(1480)在同一控制台中查找记录时,它会返回一条记录:

#<Comment id: 1480, commentable_id: 51, commentable_type: "Recipe", body: "comment content", user_id: 0, parent_id: nil, lft: nil, rgt: nil, created_at: "2006-05-16 18:48:03", updated_at: "2015-07-25 16:17:17", status: "approved", deleted_at: nil, commentable_username: "user1">

然后我试图在控制台中销毁:

Comment.find(1480).destroy(force: true)

它返回相同的错误:

  

注释加载(0.3ms)SELECT comments。* FROM comments WHERE commentsdeleted_at IS NULL和commentsid = 1480 LIMIT 1

     

(0.1ms)BEGIN

     

SQL(0.3ms)DELETE FROM comments WHERE commentsid = 1480

     

评论加载(0.2ms)SELECT comments。* FROM comments WHERE commentsid = 1480 LIMIT 1

     

(12.5ms)ROLLBACK

     

ActiveRecord :: RecordNotFound:无法找到带有'id'= 1480的评论   来自/Users/yoonwaiyan/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/activerecord-4.1.0/lib/active_record/relation/finder_methods.rb:320:in`lift_record_not_found_exception!'

这个错误很奇怪,我无法在gem和Stack Overflow上找到任何正确的解决方案。非常感谢任何帮助。

0 个答案:

没有答案