Rails 4 ActiveRecord has_many length condition

This problem seems simple, but somehow I can't wrap it around using ActiveRecord requests:

I have 2 classes with one to one relationship

class Student

  belongs_to :school

end

class School

  has_many :students, inverse_of: :school

end

      

I want to create an area that will fetch all schools that have students (in other words, their student collection size is greater than 0).

I know how to write this in SQL, but ActiveRecord made me collide. I managed to achieve this behavior on this line:

School.joins(:students)

      

but I still want to know where can I specify the condition, for example:

School.where("students.length > ?", 0)

      

+3


source to share


1 answer


Not a direct answer to your real question, but an alternative, but you get a big performance boost when counting associations by using the "counter_cache" function in rails:

class Student
  belongs_to :school, :counter_cache => true

      



You also need to add the "students_count" column to the schools table with a default of 0. Then, when the association is created / removed, this counter is automatically updated and allows simple queries:

School.where('students_count > ?, 0)

      

+1


source







All Articles