这似乎是一个简单的问题,但对我来说有点困惑:
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