find all that are nil in the association

前端 未结 7 1150
不知归路
不知归路 2021-02-04 09:01

So I have a Post and a User.
Post has_many users and a user belongs_to a post.
I need a find that will find all the Posts that dont have any users like the following:

7条回答
  •  别那么骄傲
    2021-02-04 09:31

    Learned this one just today:

    Post.eager_load(:users).merge(User.where(id: nil))
    

    Works with Rails 4+ at least.

    Update:

    In Rails 5+, you can use left_joins instead:

    Post.left_joins(:users).merge(User.where(id: nil))
    

提交回复
热议问题