Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails 4 ActiveRecord具有多个长度条件_Ruby On Rails_Ruby_Rails Activerecord - Fatal编程技术网

Ruby on rails Rails 4 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

这个问题看起来很简单,但不知何故,我无法用ActiveRecord查询来解决它:

我有两个一对多关系的类

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)