Rails find all without associations
Finding all rows in one table that has a certain amount or no associations at all is a little tricky with ActiveRecord. In fact, you just sort of have to hack it up or use find_by_sql instead. Here's a smooth solution I used to find all entries without tags and notes (as an example):
Entry.find_in_batches( :select => "entries.*", :joins => ["LEFT OUTER JOIN tags ON entries.id = tags.entry_id", "LEFT OUTER JOIN notes ON entries.id = notes.entry_id"], :conditions => "entries.entry_type = 0 and tags.id is NULL and notes.id is NULL",
:batch_size => 500
) do |batch|
# do something
end
Above, I'm using find_in_batches, which is an awesome new Rails 2.3 feature that batches your finds for you. No more limiting and offsetting manually needed! It works great. I'm using this in a daily cron to clean up weird stuff, so there is sometimes a lot of entries to play with. Read more about the Rails 2.3 release.
