Rails habtm and finding record with no association

前端 未结 2 893
囚心锁ツ
囚心锁ツ 2020-12-14 21:39

I have 2 models:

class User < ActiveRecord::Base
    has_and_belongs_to_many :groups
end

class Group < ActiveRe         


        
2条回答
  •  鱼传尺愫
    2020-12-14 21:57

    Your implicit join table would have been named groups_users based on naming conventions. Confirm it once in your db. Assuming it is:

    In newer Rails version:

    scope :not_in_any_group, -> {
        joins("LEFT JOIN groups_users ON users.id = groups_users.user_id")
        .where("groups_users.user_id IS NULL")
    }
    

    For older Rails versions:

    scope :not_in_any_group, {
        :joins      => "LEFT JOIN groups_users ON users.id = groups_users.user_id",
        :conditions => "groups_users.user_id IS NULL",
        :select     => "DISTINCT users.*"
    }
    

提交回复
热议问题