0

Suppose my Rails app have a relationship of Recipe and Comment by using acts_as_commentable_with_threading gem and that Recipe gem has paranoid2 gem configured. Migrating from old system to new system, I've created new records by manually inserting records to the Comment table, but mistakenly created duplicate comments for every recipe. Now I wanted to remove the duplicate records by modifying the solution of 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

But when I call this function in my Rails console, this function returns an error, let's say the first duplicated record has an id of 1480:

ActiveRecord::RecordNotFound: Couldn't find Comment with 'id'=1480 from /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 `raise_record_not_found_exception!'

But when I tried to find the record in the same console using Comment.find(1480), it returns a record:

#<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">

And then I tried to destroy in the console:

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

It returns the same error:

Comment Load (0.3ms) SELECT comments.* FROM comments WHERE comments.deleted_at IS NULL AND comments.id = 1480 LIMIT 1

(0.1ms) BEGIN

SQL (0.3ms) DELETE FROM comments WHERE comments.id = 1480

Comment Load (0.2ms) SELECT comments.* FROM comments WHERE comments.id = 1480 LIMIT 1

(12.5ms) ROLLBACK

ActiveRecord::RecordNotFound: Couldn't find Comment with 'id'=1480 from /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 `raise_record_not_found_exception!'

This error is weird and I couldn't find any proper solution on both gem and Stack Overflow. Any help is much appreciated.

Community
  • 1
  • 1
nayiaw
  • 1,416
  • 4
  • 17
  • 26

0 Answers0