find all that are nil in the association

前端 未结 7 1148
不知归路
不知归路 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:24
    Post.where("id not in (select post_id from users)")
    
    0 讨论(0)
  • 2021-02-04 09:25

    I know this is tagged as Rails 3, but if you are using Rails 4, I've been doing it like this.

    Post.where.not(user_id: User.pluck(:id))
    
    0 讨论(0)
  • 2021-02-04 09:28

    i guess a sql with in can cause performance problems if database table has many rows. careful with that

    0 讨论(0)
  • 2021-02-04 09:29

    something like that:

    p = Post.arel_table
    u = User.arel_table
    
    posts = Post.find_by_sql(p.join(u).on(p[:user_id].eq(u[:p_id])).where(u[:id].eq(nil)).to_sql) 
    
    0 讨论(0)
  • 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))
    
    0 讨论(0)
  • 2021-02-04 09:50

    If you need something that is fast, employ a SQL statement like:

    SELECT * 
    FROM posts p 
    LEFT OUTER JOIN users u ON p.id = u.post_id 
    WHERE u.id IS null
    
    0 讨论(0)
提交回复
热议问题