條款這似乎是一個簡單的問題,但它是一個小的難題對我說:導軌「其中」消協
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