简体   繁体   中英

Rails Console - ActiveRecord::RecordNotFound

I am trying to delete a mass amount of records from my database. My destroy_all keeps getting stopped when a callback fails to destroy a record because of ActiveRecord::RecordNotFound . I want to skip the callbacks when the error ActiveRecord::RecordNotFound occurs on records that the callback is trying to delete.

All User records belong to school via a UserSchool relation. I am trying to delete all User Records where the school_id : 74 is present in any UserSchool record.

user_ids = UserSchool.where(school_id: 74).map(&:user_id)
User.where(id: user_ids).destroy_all  

The result is:

ActiveRecord::RecordNotFound: Couldn't find Comment with 'id'=17

I want to skip over that error and continue destroying User records. How can I rescue here?

user_ids = UserSchool.where(school_id: 74).map(&:user_id)
users = User.where(id: user_ids)

users.each do |user|
  begin 
    user.destroy
  rescue => ActiveRecord::RecordNotFound
    puts "Record not found"
  end
end

I think we can rescue by looping it over each object.

user_ids.each do |user_id|
 User.find(user_id).destroy rescue nil
end

For only ActiveRecord::RecordNotFound exception you could do,

user_ids.each do |user_id|
  begin 
    Contact.find(user_id).destroy
  rescue => ActiveRecord::RecordNotFound
    puts "Record not found"
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM