Ruby on rails Rails 4 ActiveRecord具有多个长度条件
这个问题看起来很简单,但不知何故,我无法用ActiveRecord查询来解决它: 我有两个一对多关系的类Ruby on rails Rails 4 ActiveRecord具有多个长度条件,ruby-on-rails,ruby,rails-activerecord,Ruby On Rails,Ruby,Rails Activerecord,这个问题看起来很简单,但不知何故,我无法用ActiveRecord查询来解决它: 我有两个一对多关系的类 class Student belongs_to :school end class School has_many :students, inverse_of: :school end 我想创建一个范围,它将获取所有有学生的学校(换句话说,他们的学生集合大小大于0) 我知道如何用SQL写这篇文章,但ActiveRecord让我大吃一惊。 我确实做到了这一点: Schoo
class Student
belongs_to :school
end
class School
has_many :students, inverse_of: :school
end
我想创建一个范围,它将获取所有有学生的学校(换句话说,他们的学生集合大小大于0)
我知道如何用SQL写这篇文章,但ActiveRecord让我大吃一惊。
我确实做到了这一点:
School.joins(:students)
但我仍然想知道在哪里可以指定条件,例如:
School.where("students.length > ?", 0)
这不是对您实际问题的直接回答,而是一种替代方案,但使用rails中的“计数器缓存”功能,您可以在关联计数方面获得巨大的性能提升:
class Student
belongs_to :school, :counter_cache => true
您还需要在schools表中添加一个“students\u count”列,默认值为0。然后,当创建/删除关联时,此计数器将自动更新,并允许进行如下简单查询:
School.where('students_count > ?, 0)