查找具有许多关系和其他参数的记录Ruby on Rails MySQL



我有两个表,宠物和主人

class Owner < ApiModel
has_and_belongs_to_many :pets

class Pets < ApiModel
has_and_belongs_to_many :owners

所以这个例子是三个Owners,弗兰克,玛丽,希拉里,他们住在一起,有三个pets(狗,猫,鱼)

Owner1 = {name: "Mary", gender: "female", hair_color: "blue", pets: [pet1, pet2, pet3]} 
Owner2 = {name: "Hilary", gender: "female", hair_color: "green", pets: [pet1, pet2]} 
Owner3 = {name: "Frank", gender: "male", hair_color: "red", pets: [pet3]}
pet1 = {name: "doggy", gender: "female", animal: "dog"}
pet2 = {name: "kitty", gender: "male", animal: "cat"}
pet3 = {name: "fishy", gender: "male", animal: "fish"}

我的目标是返回Owner 1,因为我知道她拥有宠物3,而且她是雌性的。我想我可以这样做:

found_pet = Pet.find_by(animal: "fish") # will correctly only return the pet3 record
owner = Owner.where(hair_color: "blue").includes(pet: found_pet)

但是当我试图找到所有者时,我一直得到一个错误(Object doesn't support #inspect)

是否可以使用.join?

Rails版本6.0.4.7

Ruby版本Ruby 3.1.1p18

(在评论中回答)

Christos-Angelos Vasilopoulos对我最初的问题有一个很好的回答,但我有一个跟进。

那么如果我想找到主人拥有两只宠物的地方呢:

found_pet1 = Pet.find_by(animal: "dog")
found_pet2 = Pet.find_by(animal: "cat") 
owner = Owner.where(hair_color: "blue").includes(pet: found_pet1).includes(pet: found_pet2)

最好的方法是使用关联。执行pet_record.owners返回所有宠物的主人。然后,您需要一个查询来返回正确的结果。

使用find_by获取查询的第一条匹配记录

found_pet.owners.find_by(hair_color: "blue")

使用where获取查询的所有匹配记录

found_pet.owners.where(hair_color: "blue")

PS:在你的问题中,你的状态是你需要返回Owner1,因为它是女性,那么我建议做以下事情。

found_pet.owners.find_by(gender: "female")
found_pet.owners.where(gender: "female")

相关内容

  • 没有找到相关文章

最新更新