假设我的 Rails 应用程序使用acts_as_commentable_with_threading gem 具有Recipe 和Comment 的关系,并且Recipe gem 配置了paranoid2 gem。从旧系统迁移到新系统,我通过手动将记录插入评论表来创建新记录,但错误地为每个食谱创建了重复的评论。现在我想通过修改这个 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: 找不到来自 /Users/yoonwaiyan/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/activerecord-4.1.0/lib 的 'id'=1480 的评论/active_record/relation/finder_methods.rb:320:in `raise_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
.* FROMcomments
WHEREcomments
。deleted_at
为空且comments
。id
= 1480 限制 1(0.1ms) 开始
SQL (0.3ms) 从
comments
WHERE中删除comments
。id
= 1480评论加载 (0.2ms) SELECT
comments
.* FROMcomments
WHEREcomments
。id
= 1480 限制 1(12.5ms) 回滚
ActiveRecord::RecordNotFound: 找不到来自 /Users/yoonwaiyan/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/activerecord-4.1.0/lib 的 'id'=1480 的评论/active_record/relation/finder_methods.rb:320:in `raise_record_not_found_exception!'
这个错误很奇怪,我在 gem 和 Stack Overflow 上都找不到任何合适的解决方案。任何帮助深表感谢。