问题
I have two models: TimeLog
and Task
. TimeLog
belongs to Task
and Task
has many TimeLog
s.
In the past some Task
s were deleted but the corresponding TimeLog
s were not deleted (the cascade delete wasn't working). So we have some broken TimeLog
s. They do have a task_id
but that task_id
does not exist anymore.
I have two questions:
1) I want to get all the TimeLog
s from a user but filtering the broken ones.
i.e
TimeLog.find(:all, :conditions => ['time_log.user_id = ? and <time_log.task_id exists>])
2) I want to get all the broken TimeLog
s in the console to delete them manually.
i.e.
TimeLog.find(:all, :conditions => [<!time_log.task_id exists>])
How can I do that?
Thanks
回答1:
Add something like the following where()
to your chain of ActiveRelation
calls to include any orphaned TimeLog
s:
.where('NOT EXISTS SELECT * FROM tasks where tasks.id = timelogs.task_id')
...and obviously if you remove the NOT
you'll explicitly exclude any orphaned records.
回答2:
A rake task to track down missing database indexes: https://github.com/eladmeidar/rails_indexes
来源:https://stackoverflow.com/questions/9471395/rails-3-find-condition-to-filter-broken-reference-integrity-associations