find all that are nil in the association

前端 未结 7 1149
不知归路
不知归路 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:50

    Post.first.users.empty? should be sufficient if users returns an array.

    If you want to check for each post you could do

    Post.each do |p|
      if p.users.empty?
        do whatever
      end
    end
    
    0 讨论(0)
提交回复
热议问题