简体   繁体   中英

Rails ActiveRecord: find related model COUNT with a HABTM (has_and_belongs_to_many) relationship

I have two models

class Items < ApplicationRecord
  has_and_belongs_to_many :users
end

class Users < ApplicationRecord
  has_and_belongs_to_many :items
end

I want to find out all the items that have 2 users associated with them, and delete them.

I could think of doing it using an iterative approach like:

Item.all.each do |i|
  if i.users.all.count == 2
    i.delete
  end
end

Is there a more elegant way (oneliner?) to do this using only the ActiveRecord ORM ?

Thanks.

不确定,但以下应该有效

Item.joins(:users).group('items.id').having('COUNT(items_users.user_id) = 2').destroy_all

Use group and having for filter the condition.

Item.joins(:users)
    .group('COUNT(users.id)')
    .having('COUNT(users.id) = ?', 2)
    .select('COUNT(users.id) AS users_count')
    .destroy_all

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