Rails 3 finding parents which have no child

前端 未结 3 811
遇见更好的自我
遇见更好的自我 2020-12-06 18:57

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



        
相关标签:
3条回答
  • 2020-12-06 19:22

    I believe something like

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

    might work also...

    0 讨论(0)
  • 2020-12-06 19:34

    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.

    0 讨论(0)
  • 2020-12-06 19:45

    Try

    User.joins("left join pages on pages.user_id = users.id").where("pages.user_id is null")
    
    0 讨论(0)
提交回复
热议问题