简体   繁体   中英

Rails - Find records with only one specific associated has_many or has_and_belongs_to_many record

I am wondering how to find records with only one specific has_and_belongs_to_many item.

The associations are as follows:

class User < ActiveRecord::Base
  has_and_belongs_to_many :roles
end

class Role < ActiveRecord::Base
  has_and_belongs_to_many :users
end

The following is what I normally use.

User.includes(:roles).where(roles: {name: 'guest'})

This is not sufficient because I want to find all users with only the role guest . It should not get records that have any other roles in addition to guest .

Can someone show me the way here? Ideally the solution would be compatible with all SQL database types (mysql, mariadb, postgres, sqlite)

User.includes(:roles).where(roles: {name: 'guest'}).having("COUNT(roles.id)=1")

如果您不需要急于加载查询,我也建议使用joins而不是includes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM