ruby - 找出模型是否包含在具有 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
解决方案
像这样的东西怎么样:
def owns(_pets)
pets.where(id: _pets).size == _pets.size
end
推荐阅读
- assembly - Lisp 编译器的汇编器输出不正确
- javascript - 按下按钮即可在标记上居中地图
- python-3.x - pyinstaller .exe 构建在启动后立即停止,没有错误
- c# - ASP.NET Core 3.1 - 将子项添加到剃刀局部视图
- jquery - 如何用jquery找到最近的下一个img标签
- arrays - 为什么将数组作为实际参数发送给需要指向数组的指针的函数需要取消引用 2 次才能访问数组?
- python - 如何拆分字符串的DataFrame列以获取第n次出现子字符串后的所有内容
- xamarin - Xamarin.Forms 样式预览颜色未显示
- python - 基于具有重复键的键有效地将一个数据帧与另一个数据帧匹配
- c# - C#计算器,等号按钮不会在第二次点击时执行操作