找出模型是否包含ID数组中描述的关联

时间:2019-05-16 18:52:49

标签: ruby activerecord

我有以下型号:

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

2 个答案:

答案 0 :(得分:2)

那这样的事情呢?

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

答案 1 :(得分:0)

我建议使用此选项。

class Person < ApplicationRecord
    has_many :pets

    def owns?(_pets)
        pets_ids = pets.pluck(:id)
        _pets.all? { |id| pets_ids.include? id }
    end
end

_pets = [1, 4, 5]时,您可能遇到以下情况:

_pets =    [1, 4, 5]    # to checked
pets_ids = [1, 4]       # from pluck
#=> false


_pets =    [1, 4, 5]    # to checked
pets_ids = [1, 4, 5]    # from pluck
#=> true


_pets =    [1, 4, 5]    # to checked
pets_ids = [1, 4, 5, 6] # from pluck
#=> true