Sql 对现有集合的Rails ActiveRecord查询
假设我有一个查询结果:Sql 对现有集合的Rails ActiveRecord查询,sql,ruby-on-rails-4,rails-activerecord,mysql2,Sql,Ruby On Rails 4,Rails Activerecord,Mysql2,假设我有一个查询结果: allCourses = Course.all 然后我还有一套: myCourses = current_user.courses.all 我怎样才能得到一组包含在所有课程中而不包含在myCourses中的项目 以下是模型: class Student < ActiveRecord::Base has_many :student_enrollments, dependent: :destroy has_many :courses, through
allCourses = Course.all
然后我还有一套:
myCourses = current_user.courses.all
我怎样才能得到一组包含在所有课程中而不包含在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
class-Student
我总是可以编写原始SQL脚本来实现这个结果,但我更喜欢用Rails的方法来实现
谢谢假设您的fk是
用户id
ohterCourses = Course.where('user_id != ?', current_user.id)
或者
Course.where.not(user\u id,current\u user.id)
并不是那么简单。我有一个多对多关系的加入者模型。即使我删除了具有该用户id的记录,其他用户id也可能具有相同的课程。我刚刚用模型更新了问题。