Rails ActiveRecord查询现有集合

时间:2014-06-23 09:25:34

标签: sql ruby-on-rails-4 rails-activerecord mysql2

假设我有查询结果:

allCourses = Course.all

然后我还有另一套:

myCourses = current_user.courses.all

如何获取allCourses中的一组项目而不是myCourses?

以下是模型:

class Student < ActiveRecord::Base
    has_many :student_enrollments, dependent: :destroy
    has_many :courses, through: :student_enrollments
end

class Course < ActiveRecord::Base   
    has_many :student_enrollments, dependent: :destroy
    has_many :students, through: :student_enrollments
end

class StudentEnrollment < ActiveRecord::Base
    belongs_to :student
    belongs_to :course
end

我总是可以编写原始SQL脚本来实现结果,但我更愿意找到一种Rails方法来实现它。

由于

1 个答案:

答案 0 :(得分:0)

假设你的fk是user_id

ohterCourses = Course.where('user_id != ?', current_user.id)