Rails habtm and finding record with no association

前端 未结 2 889
囚心锁ツ
囚心锁ツ 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 22:11

    If you convert from HABTM to has_many through (more flexible) association, then you can use something like this:

    class Group < ActiveRecord::Base
      has_many :groups_users, dependent: :destroy
      has_many :users, through: :groups_users, uniq: true
    
      scope :in_groups, -> { includes(:groups_users).where(groups_users: {group_id: nil}) }
    end
    
    class User < ActiveRecord::Base
      has_many :groups_users, dependent: :destroy
      has_many :groups, through: :groups_users
    end
    
    class GroupsUser < ActiveRecord::Base
      belongs_to :group
      belongs_to :user
    end
    

提交回复
热议问题