7

In a one to many relationship with no counter cache how can I find parents with no child?

user.rb

has_many :pages

page.rb

belongs_to :user

I've tried

User.includes(:pages).where("pages.user_id is NULL")

This is making trouble in MySQL.

3 Answers 3

15

Try

User.joins("left join pages on pages.user_id = users.id").where("pages.user_id is null")
1
  • Thanks, it helped me a lot as well !
    – sidney
    Sep 5, 2017 at 8:08
0

One way would be

User.where("(SELECT COUNT(*) FROM pages WHERE pages.user_id = users.id) = 0")

But I'm not sure how (in)efficient that would be.

1
  • 2
    count(*) is not something that i'd personally want to run if it was a common query. Jul 3, 2011 at 22:32
0

I believe something like

 User.all(:joins => :comments, :select => "users.*, count(comments.id) as comments_count", :group => "users.id")

might work also...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.