[英]Finding a record with has many relationship and other params Ruby on Rails MySQL
我有兩張桌子,寵物和主人
class Owner < ApiModel
has_and_belongs_to_many :pets
和
class Pets < ApiModel
has_and_belongs_to_many :owners
所以例子是三個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"}
我的目標是返回所有者 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)
最好的方法是使用關聯。 執行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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.