ruby-on-rails – Rails“where”子句用于关联
这似乎是一个简单的问题,但这对我来说有点困惑:
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) 谢谢! *附录* 更复杂的情况是我根据更复杂的逻辑创建一个Relation,例如 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 解决方法
你可以做:
p = Parent.find(111) all_children = p.children 关键父级不起作用,因为它使用它作为列名称. 附录: 所以对于这个用例你应该使用: class ClassRoom < ActiveRecord::Base belongs_to :teacher belongs_to :child end class Teacher < ActiveRecord::Base has_many :children,through: ClassRoom has_many :class_rooms end class Child < ActiveRecord::Base has_many :class_rooms has_many :teachers,through: ClassRoom end t = Teacher.first teachers_children_from_boston_and_32 = t.children.where(age: 32,city: "boston") 首先,你不能使用Class,因为它已经是一个对象. 在这里查看连接表:http://guides.rubyonrails.org/active_record_querying.html#joining-tables 和Assoications在这里(您的用例完美匹配此示例): 还记得rails 3所有where子句只是critera. where_clause_one = Teacher.where(age: 50) where_clause_two = Teacher.where(city: "San Francisco") merged_where_clauses = where_clause_one.merge(where_clause_two) merged_where_clauses.each do |teacher| # teachers that are both 50 and from san francisco ... end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |