轨道3 - 查找条件来筛选损坏的引用完整性协会 [英] Rails 3 - Find condition to filter broken Reference integrity associations

查看:116
本文介绍了轨道3 - 查找条件来筛选损坏的引用完整性协会的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个型号: TimeLog 工作 TimeLog 属于工作工作有许多 TimeLog 秒。

I have two models: TimeLog and Task. TimeLog belongs to Task and Task has many TimeLogs.

在某些工作取值被删除了过去,但相应的 TimeLog 取值未删除(级联删除WASN 'T工作)。因此,我们有一些破 TimeLog 秒。他们有一个 TASK_ID TASK_ID 不存在了。

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.

我有两个问题:

1),我想所有的 TimeLog - 从一个用户,但过滤破的。

1) I want to get all the TimeLogs from a user but filtering the broken ones.

TimeLog.find(:all, :conditions => ['time_log.user_id = ? and <time_log.task_id exists>])

2)我想所有的破 TimeLog S在控制台中手动删除它们。

2) I want to get all the broken TimeLogs in the console to delete them manually.

TimeLog.find(:all, :conditions => [<!time_log.task_id exists>])

我怎么能这样做?

How can I do that?

感谢

推荐答案

添加类似如下其中()您的链 ActiveRelation 呼吁包括任何孤立 TimeLog S:

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.

这篇关于轨道3 - 查找条件来筛选损坏的引用完整性协会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆