Ruby on rails 基于更深关联的计数筛选嵌套关联的结果
我有以下模型和关联:Ruby on rails 基于更深关联的计数筛选嵌套关联的结果,ruby-on-rails,rails-activerecord,active-record-query,Ruby On Rails,Rails Activerecord,Active Record Query,我有以下模型和关联: class ClassProfile < ActiveRecord::Base has_many :enrollments, dependent: :destroy has_many :student_profiles, through: :enrollments class Enrollment < ActiveRecord::Base belongs_to :student_profile belongs_to :class_profi
class ClassProfile < ActiveRecord::Base
has_many :enrollments, dependent: :destroy
has_many :student_profiles, through: :enrollments
class Enrollment < ActiveRecord::Base
belongs_to :student_profile
belongs_to :class_profile
class StudentProfile < ActiveRecord::Base
has_one :enrollment, dependent: :destroy
has_one :class_profile, through: :enrollment
has_many :relationships
has_many :parent_profiles, through: :relationships
class Relationship < ActiveRecord::Base
belongs_to :student_profile
belongs_to :parent_profile
class ParentProfile < ActiveRecord::Base
has_many :relationships
has_many :student_profiles, through: :relationships
所以我想用这样一种方法:
class ClassProfile < ActiveRecord::Base
...
def orphans
self.student_profiles.where( child? == false )
end
也就是说,返回正确集合的单个语句。但这不是where的有效用法,并会引发错误。这是有意义的,因为据我所知,关联模型上的where方法只对字段有效,而不对方法有效。无论如何,这就是我要找的东西,只有真正有效的东西。也许你可以为此加入。在ClassProfile中
class ClassProfile < ActiveRecord::Base
...
def orphans
#return a collection of all student_profiles where
#there are no parent_profiles associated
#(i.e. parent_profiles.count = 0 or parent_profiles.empty? = true
end
def orphans
self.joins(student_profiles: :relationships)
end
这里的连接是一个内部连接。没有关系的学生将不会加入这里。此外,也许您可以为您的方法尝试一个更好的名称。你的名字很模糊 我知道了。以下是具有所需行为的代码:
def orphans
student_profiles.reject { |s| s.child? }
end
我相信这需要遍历所有的学生档案,而不是在查询级别工作,但是它完成了工作
def orphans
student_profiles.reject { |s| s.child? }
end