条款这似乎是一个简单的问题,但它是一个小的难题对我说:导轨“其中”消协
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
您可以添加一个范围http://guides.rubyonrails.org/active_record_querying.html#scopes或修补ActiveRecord,但最好的方式来做到这一点已经涵盖在这个页面上,我相信。 – earlonrails 2013-04-27 19:13:04