HABTM: Records with no parents

I have a habtm relationship between two models. What I want to do is
find items that aren’t related. So like if you had authors ↔
posts, how would you find authors who don’t have any posts? Or posts
that don’t have an author ?

Thanks,

Alex Strand

[[email protected]]
Razorcom


Our company, Razorcom, is developing a product called LiquiPages.
LiquiPages is a way for content owners to maintain their websites and
publish changes from a centralized location. If you are interested
in helping us with our beta test, please visit http://
www.liquipages.com/


Visit the Razorcom Blog, Revolution Trigger, at:
http://www.razorcom.com/blog/

Hi there.
Hope I get you right. Is this what you want?

authors.each do |author|
if author.posts.empty?
do_stuff
end
end

Well I think actually backwards… like, what posts have no authors?

Thanks,

Alex Strand

[[email protected]]
Razorcom


Our company, Razorcom, is developing a product called LiquiPages.
LiquiPages is a way for content owners to maintain their websites and
publish changes from a centralized location. If you are interested
in helping us with our beta test, please visit http://
www.liquipages.com/


Visit the Razorcom Blog, Revolution Trigger, at:
http://www.razorcom.com/blog/

On 2006-01-23 19:16:47 -0500, Razorcom
[email protected] said:

Well I think actually backwards… like, what posts have no authors?

I would strongly recommend agaisnt this method, which is very consuming
in terms of processing. If your DBMS allows subqueries (mySQL 4.1+
does, iirc), try the following:

Post.find :all, :conditions => “id NOT IN (SELECT DISTINCT post_id FROM
authors_posts)”

This will give you an array of all Post objects whose ids do not show
up in the join table.

The opposite (authors without any posts):

Author.find :all, :conditions => “id NOT IN (SELECT DISCINT author_id
FROM authors_posts)”

This technique is MUCH faster, and you still get full-featured
ActiveRecords objects. Don’t fear SQL when it can really help out :slight_smile:

Note that you could also use a counter cache (see Rails api doc) if
subqueries are not available.

Ben