Rails 3 - find a condition for filtering broken integrity link associations

I have two models: TimeLog and Task . TimeLog owned by Task , and Task has many TimeLog s.

In the past, some Task were deleted, but the corresponding TimeLog were not deleted (cascading deletion did not work). So, we have broken TimeLog s. They have task_id , but task_id no longer exists.

I have two questions:

1) I want to get all TimeLog from the user, but filter out the broken ones.

ie

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

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

i.e.

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

How can i do this?

thanks

+1
ruby activerecord ruby-on-rails-3
source share
2 answers

Add the following where() line to the ActiveRelation call chain to include any lost TimeLog s:

 .where('NOT EXISTS SELECT * FROM tasks where tasks.id = timelogs.task_id') 

... and, obviously, if you delete NOT , you explicitly exclude any lost entries.

+3
source share

Rake task to track missing database indexes: https://github.com/eladmeidar/rails_indexes

0
source share

All Articles