简体   繁体   中英

Display Users without Posts in Rails

How would I query my Users who have yet to write any posts? This is what I am trying:

u = User.joins(:posts).where('posts.size = ?', 0)

Output:

PG::UndefinedColumn: ERROR:  column posts.size does not exist

Trying to wrap my head around the correct SQL syntax, but no luck so far

You must do this without a join, like this:

 User.where(Post.where("posts.user_id = users.id").exists.not)

Its very useful to chain conditions (like applying different filters).


creates SQL like:

SELECT "users".* FROM "users"  
WHERE (
  NOT (
    EXISTS (SELECT "posts".* FROM "posts"  WHERE (posts.user_id = users.id))
  )
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM