开发者

Rails 3 finding parents which have no child

开发者 https://www.devze.com 2023-03-16 21:11 出处:网络
In a one to many relationship with no counter cache how can I find parents with no child? user.rb has_many :pages

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 makin开发者_如何学Pythong trouble in MySQL.


Try

User.joins("left join pages on pages.user_id = users.id").where("pages.user_id is null")


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.


I believe something like

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

might work also...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号