这似乎是一个简单的问题,但对我来说却是一个小难题:
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
最佳答案
.all
将 ActiveRecord::Relation 对象转换为数组。数组不响应 where
方法。你应该使用
c = Child.where(parent_id: p.id).all
在这种情况下你必须使用 _id 因为
where
将直接将给定的哈希转换为 SQL。 SQL不知道什么parent
是,它只知道什么parent_id
是。话虽如此,最好的方法是c = p.children
关于ruby-on-rails - Rails "where"关联子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16244411/