首页 > 解决方案 > 找出模型是否包含在具有 ids 的数组中描述的关联

问题描述

我有以下型号:

class Person < ApplicationRecord
    has_many :pets
end

class Pet < ApplicationRecord
    belongs_to :person
end

现在我有一个包含某些宠物 id 的数组,我想检查这个人是否拥有它们。

_pets = [1, 4, 5]

person.owns(_pets)

所以现在我想知道如何检查用户是否拥有所有这些宠物。这意味着我想知道是否_pets是他所有宠物的一个子集。

class Person < ApplicationRecord
    has_many :pets

    def owns(_pets)
        # ???
        # Returns true or false
    end
end

class Pet < ApplicationRecord
    belongs_to :person
end

标签: rubyactiverecord

解决方案


像这样的东西怎么样:

def owns(_pets)
  pets.where(id: _pets).size == _pets.size
end

推荐阅读