これは簡単な質問のように思えますが、私にはちょっとしたパズルです:
class Parent
has_many children
...
end
class Child
belongs_to parent
end
p = Parent.find(111)
c = Child.all.where(parent: p)
なぜそれがうまくいかないのか、なぜ私はしなければならないのか:
c = Child.all.where(parent_id: p.id)
補遺
より複雑なケースでは、より複雑なロジックに基づいて関係を作成する必要があります。
c = Child.where(age: 32, city: "boston")
c.where(parent: p) # wouldn't work
補遺#2
これを説明するには、多対多にする必要があります。
class Teacher
has_many :students, through: ClassRoom
has_many :classes
end
class ClassRoom
belongs_to :teacher
belongs_to :child
end
class Child
has_many :classes
has_many :teachers, through: ClassRoom
end
t = Teacher.first
c = Child.where(age: 5, city: "boston")
c.where(teacher: t) # wouldn't work
c.where(teacher_id: t.id) # would work but is a little ugly
補遺3
素晴らしい情報をありがとう!上記の例の最後の行を実行するためのより良い (または「正しい」) 方法はありますか?
c.where(teacher_id: t.id) # would work but is a little ugly