Enrique Moreno Tent
Enrique Moreno Tent

Reputation: 25237

Find out if a model contains associations described in an array with ids

I have the following models:

class Person < ApplicationRecord
    has_many :pets
end

class Pet < ApplicationRecord
    belongs_to :person
end

Now I have an array with the ids of certain pets, and I want to check if the person owns them all.

_pets = [1, 4, 5]

person.owns(_pets)

So now I want to find out how to check if the user owns ALL these pets. These means that I want to find out if _pets is a subset of all his pets.

class Person < ApplicationRecord
    has_many :pets

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

class Pet < ApplicationRecord
    belongs_to :person
end

Upvotes: 1

Views: 58

Answers (2)

iGian
iGian

Reputation: 11183

I'd suggest this option.

class Person < ApplicationRecord
    has_many :pets

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

When _pets = [1, 4, 5] you can have the following cases:

_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

Upvotes: 0

spickermann
spickermann

Reputation: 106802

What about something like this:

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

Upvotes: 2

Related Questions