Rails 3 - Find condition to filter broken Reference integrity associations

a 夏天 提交于 2019-12-24 16:41:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!