[英]Finding a record with has many relationship and other params Ruby on Rails MySQL
I have two tables, pets and owners我有两张桌子,宠物和主人
class Owner < ApiModel
has_and_belongs_to_many :pets
and和
class Pets < ApiModel
has_and_belongs_to_many :owners
So the example is three Owners
, Frank, Mary, Hillary, who live together and own three pets
(doggy, kitty, and fishy)所以例子是三个
Owners
,Frank、Mary、Hillary,他们住在一起并拥有三只pets
(doggy、kitty 和 fishy)
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"}
My goal is to return Owner 1 given that I know she owns pet3 and that she is female.我的目标是返回所有者 1,因为我知道她拥有 pet3 并且她是女性。 I thought I could do something like this:
我以为我可以做这样的事情:
found_pet = Pet.find_by(animal: "fish") # will correctly only return the pet3 record
owner = Owner.where(hair_color: "blue").includes(pet: found_pet)
But I keep getting an error (Object doesn't support #inspect)
when trying to find owner.但是在尝试查找所有者时,我不断收到错误
(Object doesn't support #inspect)
。
Is this maybe possible with using .join
?使用
.join
可能吗?
Rails version 6.0.4.7 Rails 版本 6.0.4.7
Ruby version ruby 3.1.1p18 Ruby 版本 ruby 3.1.1p18
UPDATE (Answered in Comments)更新(在评论中回答)
Christos-Angelos Vasilopoulos had a good response for my original question but I had a follow up. Christos-Angelos Vasilopoulos 对我最初的问题做出了很好的回应,但我进行了跟进。
So what if I want to find where the owner own two pets:那么如果我想找到主人拥有两只宠物的地方怎么办:
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)
The best approach would be to use the association.最好的方法是使用关联。 Executing
pet_record.owners
returns all the pet owners.执行
pet_record.owners
返回所有宠物主人。 Then you need a query to return the right results.然后你需要一个查询来返回正确的结果。
Use find_by
to get the first matching record for your query使用
find_by
获取查询的第一条匹配记录
found_pet.owners.find_by(hair_color: "blue")
Use where
to get all the matching records for your query使用
where
获取查询的所有匹配记录
found_pet.owners.where(hair_color: "blue")
PS: In your question your state that you need to return Owner1 as it is female, then I would suggest doing the following. PS:在您的问题中,您需要将 Owner1 作为女性返回,那么我建议您执行以下操作。
found_pet.owners.find_by(gender: "female")
found_pet.owners.where(gender: "female")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.