我有兩張桌子,寵物和主人
class Owner < ApiModel
has_and_belongs_to_many :pets
和
class Pets < ApiModel
has_and_belongs_to_many :owners
所以例子是三個Owners,弗蘭克、瑪麗、希拉里,他們住在一起并擁有三個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"}
我的目標是回傳所有者 1,因為我知道她擁有 pet3 并且她是女性。我以為我可以做這樣的事情:
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)
uj5u.com熱心網友回復:
最好的方法是使用關聯。執行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")
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/489663.html
