问题
I have two models: TimeLog and Task. TimeLog belongs to Task and Task has many TimeLogs.
In the past some Tasks were deleted but the corresponding TimeLogs were not deleted (the cascade delete wasn't working). So we have some broken TimeLogs. 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 TimeLogs 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 TimeLogs 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 TimeLogs:
.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