[英]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
. 当回调由于
ActiveRecord::RecordNotFound
而无法销毁记录时,我的destroy_all会不断停止。 I want to skip the callbacks when the error ActiveRecord::RecordNotFound
occurs on records that the callback is trying to delete. 当回调试图删除的记录上出现错误
ActiveRecord::RecordNotFound
时,我想跳过回调。
All User records belong to school via a UserSchool relation. 所有用户记录都通过UserSchool关系属于学校。 I am trying to delete all User Records where the
school_id
: 74 is present in any UserSchool record. 我正在尝试删除所有
school_id
记录中出现school_id
:74的所有用户记录。
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, 对于您只能执行的
ActiveRecord::RecordNotFound
异常,
user_ids.each do |user_id|
begin
Contact.find(user_id).destroy
rescue => ActiveRecord::RecordNotFound
puts "Record not found"
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.