未在另一个模型中引用的模型的 ActiveRecord 查询

ActiveRecord query for model not referenced in another model

我有类似以下2款的东西:

class Person < ActiveRecord::Base
  has_one :student
end
class Student < ActiveRecord::Base
  belongs_to :person
end

我知道我可以找到所有学生:

Person.joins(:student)

如何找到所有 不是 学生的人?有没有一种方法可以使用 ActiveRecord 执行此操作而不必编写 SQL 查询?

因为你使用 rails 4 你可以这样做:

Person.where.not(:id => Student.select(:person_id))

使用这个语句:

Person.includes(:student).
       where(:students => {:id => nil})

Person.joins("LEFT JOIN students ON students.person_id = people.id").
       where(:students => {:id => nil})

我更喜欢后者,因为它没有 select 不需要的列。