Jan
Jan

Reputation: 6828

How to query for a unfulfilled habtm relation?

I have Posts and Tags (Active Record using the Mysql adapter) in a HABTM relation. How should I query for Posts that have no Tags?

Upvotes: 1

Views: 48

Answers (1)

Thomas Klemm
Thomas Klemm

Reputation: 10856

You could try including the tags in your query and then iterating over the array selecting only the posts with no tags associated.

Post.includes(:tags).select { |post| post.tags.empty? }

Note: You can also have a look at this question where I suggested an answer along these lines earlier today. Maybe some other, potentially more efficient ideas, roll in there, too. Funny how those questions fall together sometimes :-D.

Upvotes: 1

Related Questions